try {
FileInputStream fis = new FileInputStream("C://Users/lenovo/Desktop/aa.txt");
//获取文件读写通道
FileChannel fc = fis.getChannel();
//创建字节缓冲区
ByteBuffer bf = ByteBuffer.allocate(16);
//创建char缓冲区
CharBuffer cb = CharBuffer.allocate(16);
char[] a = null;
//获取字符集编码对象
Charset charset = Charset.forName("utf-8");
//为charset创建新的解码构造器
CharsetDecoder charsetDecoder = charset.newDecoder();
//通过通道写入缓存
int s = fc.read(bf);
while (s !=-1) {
//调用flip()方法变为读模式
bf.flip();
//从给定的输入缓冲区解码尽可能多的字节,将结果写入给定的输出缓冲区。
charsetDecoder.decode(bf, cb, true);
cb.flip();
a = new char[cb.length()];
while(cb.hasRemaining()){
cb.get(a);
System.out.print(new String(a));
}
//清空缓存区 还可以调用compact()方法清空读取过的缓存区数据 ,clear()清空所有
cb.clear();
bf.clear();
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
本文介绍了一个使用Java进行文件读取的例子,并详细展示了如何利用FileInputStream、FileChannel和ByteBuffer来读取文件内容,同时通过CharsetDecoder实现从字节到字符的解码过程。

356

被折叠的 条评论
为什么被折叠?



