FileChannel: write(MappedByteBuffer buffer)
abstract int write(ByteBuffer src)
- Writes a sequence of bytes to this channel from the given buffer.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String args[]) {
FileInputStream fIn;
FileOutputStream fOut;
FileChannel fIChan, fOChan;
long fSize;
MappedByteBuffer mBuf;
try {
fIn = new FileInputStream(args[0]);
fOut = new FileOutputStream(args[1]);
fIChan = fIn.getChannel();
fOChan = fOut.getChannel();
fSize = fIChan.size();
mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
fOChan.write(mBuf); // this copies the file
fIChan.close();
fIn.close();
fOChan.close();
fOut.close();
} catch (IOException exc) {
System.out.println(exc);
System.exit(1);
} catch (ArrayIndexOutOfBoundsException exc) {
System.out.println("Usage: Copy from to");
System.exit(1);
}
}
}
write(ByteBuffer buffer)
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
public static void main(String args[]) {
FileOutputStream fileOutputStream;
FileChannel fileChannel;
ByteBuffer byteBuffer;
try {
fileOutputStream = new FileOutputStream("test.txt");
fileChannel = fileOutputStream.getChannel();
byteBuffer = ByteBuffer.allocateDirect(26);
for (int i = 0; i < 26; i++)
byteBuffer.put((byte) ('A' + i));
byteBuffer.rewind();
fileChannel.write(byteBuffer);
fileChannel.close();
fileOutputStream.close();
} catch (IOException exc) {
System.out.println(exc);
}
}
}
Home
Java Book
File Stream
Java Book
File Stream
FileChannel:
- FileChannel
- FileChannel.MapMode.READ_WRITE
- FileChannel: close()
- FileChannel: lock(long position, long size, boolean shared)
- FileChannel: map(MapMode mode, long position, long size)
- FileChannel: position()
- FileChannel: position(long newPosition)
- FileChannel: read(ByteBuffer dst)
- FileChannel: size()
- FileChannel: transferFrom(ReadableByteChannel src, long position, long count)
- FileChannel: transferTo(long position, long count, WritableByteChannel target)
- FileChannel: tryLock()
- FileChannel: write(MappedByteBuffer buffer)