FileChannel可以用来读取文件,
RandomAccessFile file;
{
try {
file = new RandomAccessFile("C:\\Users\\大鸡腿\\Desktop\\a.txt", "rw");
FileChannel fileChannel = file.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int bytereds = fileChannel.read(byteBuffer);
while (bytereds != -1) {
System.out.println("READ:"+bytereds);
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
System.out.print(Charset.forName("UTF-8").decode(byteBuffer).toString());
}
byteBuffer.clear();
bytereds = fileChannel.read(byteBuffer);
}
file.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
其中的Buffer flip()作用有两个:
1. 把limit设置为当前的position值
2. 把position设置为0
然后处理的数据就是从position到limit直接的数据,也就是你刚刚读取过来的数据
这里还涉及到buffer的中文乱码处理:
Charset.forName("UTF-8").decode(byteBuffer).toString()