Java ByteBuffer Copy copyFileByMappedByteBuffer(String srcFileName, String dstFileName)

Here you can find the source of copyFileByMappedByteBuffer(String srcFileName, String dstFileName)

Description

copy File By Mapped Byte Buffer

License

Apache License

Declaration

public static void copyFileByMappedByteBuffer(String srcFileName, String dstFileName) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.Closeable;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class Main {
    public final static int COPY_FILE_SIZE = 1024 * 1024;

    public static void copyFileByMappedByteBuffer(String srcFileName, String dstFileName) throws IOException {
        FileChannel inFileChannel = new RandomAccessFile(srcFileName, "r").getChannel();
        FileChannel outFileChannel = new RandomAccessFile(dstFileName, "rw").getChannel();
        try {/*  w ww  . j  ava2  s. c o m*/
            long fileSize = inFileChannel.size();
            long position = 0;
            //MappedByteBuffer mappedByteBuffer = outFileChannel.map(MapMode.READ_WRITE, 0, fileSize);
            //((DirectBuffer)mappedByteBuffer).cleaner().clean();
            while (position < fileSize) {
                long copyFileSize = Math.min((fileSize - position), COPY_FILE_SIZE);
                MappedByteBuffer mappedByteBuffer = outFileChannel.map(MapMode.READ_WRITE, position, copyFileSize);
                inFileChannel.read(mappedByteBuffer);
                position += mappedByteBuffer.position();
            }
        } finally {
            closeStream(outFileChannel);
        }
    }

    public static void closeStream(Closeable... streams) {
        if (streams == null)
            return;
        for (Closeable stream : streams) {
            CloseOneStream(stream);
        }
    }

    private static void CloseOneStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. copyByteBuffer(java.nio.ByteBuffer data)
  2. copyBytes(ByteBuffer bytes)
  3. copyBytes(ByteBuffer src, ByteBuffer dst, int length)
  4. copyBytesFrom(ByteBuffer bb)
  5. copyContentsToArray(ByteBuffer src)
  6. copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length)
  7. copyFromBufferToBuffer(ByteBuffer out, ByteBuffer in, int sourceOffset, int length)
  8. copyFromStreamToBuffer(ByteBuffer out, DataInputStream in, int length)
  9. copyOf(ByteBuffer payload)