FileChannel read
In this chapter you will learn:
- How to map FileChannel to memory
- How to read content from FileChannel to a ByteBuffer
- Transfers bytes into channel's file from the given readable byte channel
Map FileChannel to memory
abstract MappedByteBuffer map(FileChannel.MapMode mode, long position, long size)
maps a region of this channel's file directly into memory.
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
//from j a v a 2 s . c o m
public class Main {
public static void main(String[] args) throws IOException {
FileChannel fc = new RandomAccessFile(new File("temp.tmp"), "rw").getChannel();
IntBuffer ib = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size()).asIntBuffer();
ib.put(0);
for (int i = 1; i < 10; i++)
ib.put(ib.get(i - 1));
fc.close();
}
}
Read content from FileChannel to a ByteBuffer
abstract int read(ByteBuffer dst)
Reads a sequence of bytes from this channel into the given buffer.
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/* j av a 2 s . c o m*/
public class Main {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
FileChannel fc = new FileInputStream("data.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
while (buff.hasRemaining())
System.out.print((char) buff.get());
}
}
Transfers bytes into channel's file from readable byte channel
abstract long transferFrom(ReadableByteChannel src, long position, long count)
transfers bytes into channel's file from the given readable byte channel.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
/* j a va2 s . c om*/
public class Main {
public static void main(String[] args) {
FileChannel in = null;
FileChannel out = null;
if (args.length < 2) {
System.out.println("Usage: java Copy <from> <to>");
System.exit(1);
}
try {
in = new FileInputStream(args[0]).getChannel();
out = new FileOutputStream(args[1]).getChannel();
out.transferFrom(in, 0L, (int) in.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Next chapter...
What you will learn in the next chapter:
- How to write ByteBuffer to a FileChannel
- Transfers bytes from this channel's file to the given writable byte channel
Home » Java Tutorial » NIO