1,buffer相关操作:
private static void bufferTest() {
IntBuffer buffer = IntBuffer.allocate(100);
System.out.println("buffer position:" + buffer.position() + ",buffer limit:" + buffer.limit()
+ ",buffer capacity:" + buffer.capacity());
buffer.put(10);
int[] data = { 10, 2, 3, 4, 5, 6, 5, 6, 7, 8 };
buffer.put(data);
System.out.println("buffer position:" + buffer.position() + ",buffer limit:" + buffer.limit()
+ ",buffer capacity:" + buffer.capacity());
buffer.flip();
System.out.println("buffer position:" + buffer.position() + ",buffer limit:" + buffer.limit()
+ ",buffer capacity:" + buffer.capacity());
while (buffer.hasRemaining()) {
System.out.println(buffer.get());
}
}
2,channel写数据相关操作:
private static void channelWriteTest() throws Exception {
String[] data = { “hadoop”, “spark”, “scala”, “bigdata”, “大数据” };
File file = new File(“d://nio_channel.txt”);
FileOutputStream out = new FileOutputStream(file);
FileChannel channel = out.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
for (String str : data) {
buffer.put((str + “\t”).getBytes(“UTF-8”));
}
buffer.flip();
channel.write(buffer);
channel.close();
out.close();
}
3,channel 读数据相关操作:
private static void chanelReadTest() throws Exception {
File file = new File("D://settings.xml");
FileInputStream inputStream = new FileInputStream(file);
FileChannel channel = inputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);
int tmp = 0;
while ((tmp = channel.read(buffer)) != -1) {
buffer.flip();
channel.read(buffer);
Charset charset = null;
CharsetDecoder decoder = null;
CharBuffer charBuffer = null;
charset = Charset.forName("UTF-8");
decoder = charset.newDecoder();
// charBuffer = decoder.decode(buffer);//用这个的话,只能输出来一次结果,第二次显示为空
charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
System.out.println(charBuffer.toString());
buffer.clear();
}
inputStream.close();
}
4,内存映射的方式读取文件:
private static void chanelMapTest() throws Exception {
File file = new File("D://settings.xml");
FileInputStream inputStream = new FileInputStream(file);
FileChannel fileChannel = inputStream.getChannel();
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());//将文件映射到内存
byte[] data = new byte[(int)file.length()];
int index = 0;
while(buffer.hasRemaining()){
data[index++] = buffer.get();
}
System.out.println(new String(data,"UTF-8"));
inputStream.close();
}
总结:
java nio 读写数据基于buffer,channel,来实现,channel是双向的,既可以把数据读入缓存区,也可以把缓存区的数据写入channel。
java读取文件的几种方式比较:
1,RundomAccessFile,读取文件较慢,能随机访问文件内容
2,传统java io操作,inputstream 读取文件较慢,效率不高
3,BufferderReader,包装读取文件较快
4,MappedByteBuffer 通过内存映射的方式读取文件最快,最为方便,如上第4中方式。