Example usage for java.io RandomAccessFile write

List of usage examples for java.io RandomAccessFile write

Introduction

In this page you can find the example usage for java.io RandomAccessFile write.

Prototype

public void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this file.

Usage

From source file:Main.java

public static void main(String[] args) {
    try {//from   ww w  . j  av a2s  . c  o  m
        byte[] b = { 1, 2, 3, 4, 5, 6 };

        RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

        // write 2 bytes in the file
        raf.write(b, 2, 2);

        // set the file pointer at 0 position
        raf.seek(0);

        // print the two bytes we wrote
        System.out.println(raf.readByte());
        System.out.println(raf.readByte());
        raf.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}

From source file:Main.java

public static boolean appendFile(String filename, byte[] data, int datapos, int datalength) {
    try {/*  w w  w .  j a  v  a  2 s.  c  o m*/

        createFile(filename);

        RandomAccessFile rf = new RandomAccessFile(filename, "rw");
        rf.seek(rf.length());
        rf.write(data, datapos, datalength);
        if (rf != null) {
            rf.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}

From source file:Main.java

public static void readStreamToFile(InputStream inStream, String filePath) throws Exception {
    File file = new File(filePath + ".wei");
    RandomAccessFile outStream = new RandomAccessFile(file, "rw");
    outStream.seek(0);/*from  w  w  w. java2  s  .c om*/
    byte[] buffer = new byte[1024];
    int len = -1;
    while ((len = inStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }
    outStream.close();
    inStream.close();
    file.renameTo(new File(filePath));
    return;
}

From source file:Main.java

/**
 * Copies an input stream to a random access file. When the reading is done,
 * the input stream is closed.//from ww w  .  j a va 2 s  .c  o  m
 * 
 * @param inputStream
 *            The input stream.
 * @param randomAccessFile
 *            The random access file.
 * @throws IOException
 */
public static void copy(InputStream inputStream, java.io.RandomAccessFile randomAccessFile) throws IOException {
    int bytesRead;
    byte[] buffer = new byte[2048];

    while ((bytesRead = inputStream.read(buffer)) > 0) {
        randomAccessFile.write(buffer, 0, bytesRead);
    }

    inputStream.close();
}

From source file:Main.java

public static boolean saveApk(File apk, String savePath) {
    FileInputStream in = null;//  w  w  w .  ja v a 2 s .c o m
    RandomAccessFile accessFile = null;
    try {
        in = new FileInputStream(apk);
        byte[] buf = new byte[1024 * 4];
        int len;
        File file = new File(savePath);
        accessFile = new RandomAccessFile(file, "rw");
        FileDescriptor fd = accessFile.getFD();
        while ((len = in.read(buf)) != -1) {
            accessFile.write(buf, 0, len);
        }
        fd.sync();
        accessFile.close();
        in.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        try {
            if (in != null) {
                in.close();
            }
            if (accessFile != null) {
                accessFile.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestNameNodeRecovery.java

static final void pad(RandomAccessFile rwf, byte b, int amt) throws IOException {
    byte buf[] = new byte[1024];
    for (int i = 0; i < buf.length; i++) {
        buf[i] = 0;/*from  w ww .  ja v a  2 s  . c om*/
    }
    while (amt > 0) {
        int len = (amt < buf.length) ? amt : buf.length;
        rwf.write(buf, 0, len);
        amt -= len;
    }
}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * //from ww  w. j a va2  s  .c o m
 * @param inputStream
 * @param raf
 * @param bufferSize
 * @return String
 * @throws Exception
 */
public static String copy(InputStream inputStream, RandomAccessFile raf, int bufferSize) throws Exception {
    int length = 0;
    byte[] bytes = new byte[Math.max(bufferSize, bufferSize)];
    MessageDigest messageDigest = MessageDigest.getInstance("md5");

    while ((length = inputStream.read(bytes)) > -1) {
        raf.write(bytes, 0, length);
        messageDigest.update(bytes, 0, length);
    }
    return Hex.encode(messageDigest.digest());
}

From source file:org.apache.flume.channel.file.Serialization.java

/**
 * Copy a file using a 64K size buffer. This method will copy the file and
 * then fsync to disk//from w w w. j  a v  a  2  s  . co  m
 * @param from File to copy - this file should exist
 * @param to Destination file - this file should not exist
 * @return true if the copy was successful
 */
public static boolean copyFile(File from, File to) throws IOException {
    Preconditions.checkNotNull(from, "Source file is null, file copy failed.");
    Preconditions.checkNotNull(to, "Destination file is null, " + "file copy failed.");
    Preconditions.checkState(from.exists(), "Source file: " + from.toString() + " does not exist.");
    Preconditions.checkState(!to.exists(), "Destination file: " + to.toString() + " unexpectedly exists.");

    BufferedInputStream in = null;
    RandomAccessFile out = null; //use a RandomAccessFile for easy fsync
    try {
        in = new BufferedInputStream(new FileInputStream(from));
        out = new RandomAccessFile(to, "rw");
        byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
        int total = 0;
        while (true) {
            int read = in.read(buf);
            if (read == -1) {
                break;
            }
            out.write(buf, 0, read);
            total += read;
        }
        out.getFD().sync();
        Preconditions.checkState(total == from.length(),
                "The size of the origin file and destination file are not equal.");
        return true;
    } catch (Exception ex) {
        LOG.error("Error while attempting to copy " + from.toString() + " to " + to.toString() + ".", ex);
        Throwables.propagate(ex);
    } finally {
        Throwable th = null;
        try {
            if (in != null) {
                in.close();
            }
        } catch (Throwable ex) {
            LOG.error("Error while closing input file.", ex);
            th = ex;
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
            LOG.error("Error while closing output file.", ex);
            Throwables.propagate(ex);
        }
        if (th != null) {
            Throwables.propagate(th);
        }
    }
    // Should never reach here.
    throw new IOException("Copying file: " + from.toString() + " to: " + to.toString() + " may have failed.");
}

From source file:com.ettrema.zsync.UploadReader.java

/**
 * Reads a number of bytes from the InputStream equal to the size of the specified Range and
 * writes them into that Range of the RandomAccessFile.
 * //from   w w w  .java 2  s  .  c o m
 * @param dataIn The InputStream containing the data to be copied
 * @param range The target location in the RandomAccessFile
 * @param buffer A byte array used to transfer data from dataIn to fileOut
 * @param fileOut A RandomAccessFile for the File being assembled
 * @throws IOException
 */
private static void sendBytes(InputStream dataIn, Range range, byte[] buffer, RandomAccessFile fileOut)
        throws IOException {

    long bytesLeft = (range.getFinish() - range.getStart());
    int bytesRead = 0;
    int readAtOnce = 0;

    fileOut.seek(range.getStart());

    while (bytesLeft > 0) {

        readAtOnce = (int) Math.min(buffer.length, bytesLeft);
        bytesRead = dataIn.read(buffer, 0, readAtOnce);
        fileOut.write(buffer, 0, bytesRead);
        bytesLeft -= bytesRead;

        if (bytesLeft > 0 && bytesRead < 0) {

            throw new RuntimeException("Unable to copy byte Range: " + range.getRange()
                    + ". End of InputStream reached with " + bytesLeft + " bytes left.");
        }
    }
}

From source file:ch.cyberduck.core.io.FileBuffer.java

@Override
public synchronized int write(final byte[] chunk, final Long offset) throws IOException {
    final RandomAccessFile file = random();
    file.seek(offset);//from  w  w w . j a va 2 s  .c om
    file.write(chunk, 0, chunk.length);
    length = Math.max(length, file.length());
    return chunk.length;
}