使用java NIO进行读文件
发布时间:2020-05-24 22:04:07 所属栏目:Java 来源:互联网
导读:使用java NIO进行读文件
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 Java NIO非堵塞技术实际是采取Reactor模式,或者说是Observer模式为我们监察I/O端口,如果有内容进来,会自动通知我们,这样,我们就不必开启多个线程死等,从外界看,实现了流畅的I/O读写,不堵塞了。 这段代码是使用java NIo读一个文件的简单应用。 public static String readUseNIO(File file) {
FileInputStream fin;
String string = null;
try {
fin = new FileInputStream(file);
FileChannel channel = null;
channel = fin.getChannel();
// 文件内容的大小
int size = (int) channel.size();
// 获取通道
FileChannel fc = fin.getChannel();
// 创建缓冲区
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 1);
// 读取数据到缓冲区
fc.read(buffer);
// Buffer bf = buffer.flip();
// System.out.println("limt:" + bf.limit());
byte[] bt = buffer.array();
string = new String(bt,size,"UTF-8");
// System.out.println(new String(bt,size));
// FileUtil.appendString("F:/html/22.html",new String(bt,// size));
buffer.clear();
buffer = null;
fin.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return string;
}
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
