
正文
java nio通过ByteBuffer输出文件信息
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
1.通过ByteBuffer的get()方法每次读取一个字节转换成char类型输出.
fc = new FileInputStream("src/demo20/data.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
buff = ByteBuffer.allocateDirect(BSIZE);
fc.read(buff);
buff.flip();
while (buff.hasRemaining()) {
System.out.print((char)buff.get());
}
2.使用系统字符集进行解码
FileChannel fc = new FileOutputStream("src/demo20/data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text".getBytes()));
buff.rewind();
String encoding = System.getProperty("file.encoding");//获取系统字符集
System.out.println("Decoded using "+ encoding + ":" + Charset.forName(encoding).decode(buff));//Decoded using GBK:Some text
fc = new FileInputStream("src/demo20/data.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
buff = ByteBuffer.allocateDirect(BSIZE);
fc.read(buff);
buff.flip();
while (buff.hasRemaining()) {
System.out.print((char)buff.get());
}
FileChannel fc = new FileOutputStream("src/demo20/data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text".getBytes()));
buff.rewind();
String encoding = System.getProperty("file.encoding");//获取系统字符集
System.out.println("Decoded using "+ encoding + ":" + Charset.forName(encoding).decode(buff));//Decoded using GBK:Some text
System.getProperty可以获取系统字符集,可以用产生系统字符集的CharSet对象,来进行解码操作.
3.写入时进行编码
fc = new FileOutputStream("src/demo20/data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
fc.close();
fc = new FileInputStream("src/demo20/data2.txt").getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
fc = new FileOutputStream("src/demo20/data2.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
fc.close();
fc = new FileInputStream("src/demo20/data2.txt").getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
ByteBuffer.wrap()方法将 ""UTF-16BE"编码的 byte 数组包装到缓冲区中,写入文件,转换成CharBuffer即可读取文件.
4.通过CharBuffer写入
fc = new FileOutputStream("src/demo20/data2.txt").getChannel();
buff = ByteBuffer.allocate(24);
buff.asCharBuffer().put("Some text");
fc.write(buff);
fc.close();
fc = new FileInputStream("src/demo20/data2.txt").getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
fc = new FileOutputStream("src/demo20/data2.txt").getChannel();
buff = ByteBuffer.allocate(24);
buff.asCharBuffer().put("Some text");
fc.write(buff);
fc.close();
fc = new FileInputStream("src/demo20/data2.txt").getChannel();
buff.clear();
fc.read(buff);
buff.flip();
System.out.println(buff.asCharBuffer());
buff分配了24个字节,能储存12个字符,写入Some text可以通过FileInputStream获取的通道读取.








