copy Bytes from RandomAccessFile to another RandomAccessFile - Android java.io

Android examples for java.io:RandomAccessFile

Description

copy Bytes from RandomAccessFile to another RandomAccessFile

Demo Code

/*/*  w  ww  .  ja v a2  s  . c o m*/
 * Java build tools related to the Android operating system.
 * Copyright (C) 2011 DivDE <divde@free.fr>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.book2s;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.MessageDigest;

public class Main {
    public static int COPY_CHUNK_SIZE = 10000;

    public static void copyBytes(RandomAccessFile srcFile,
            RandomAccessFile dstFile, int length,
            MessageDigest messageDigest) throws IOException {
        byte[] chunk = new byte[Math.min(length, COPY_CHUNK_SIZE)];
        while (length > 0) {
            int sizeToRead = Math.min(length, COPY_CHUNK_SIZE);
            int sizeRead = srcFile.read(chunk, 0, sizeToRead);
            if (sizeRead == -1) {
                throw new IOException(
                        String.format(
                                "End of source file reached too early. Still %d bytes to read.",
                                length));
            }
            if (messageDigest != null) {
                messageDigest.update(chunk, 0, sizeRead);
            }
            dstFile.write(chunk, 0, sizeRead);
            length -= sizeRead;
        }
    }
}

Related Tutorials