zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用java NIO进行读文件详解编程语言

JAVA文件nio编程语言 使用 详解 进行
2023-06-13 09:20:29 时间

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, 0, size,"UTF-8"); 

 // System.out.println(new String(bt, 0, size)); 

 // FileUtil.appendString("F:/html/22.html", new String(bt, 0, 

 // 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; 

 }

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10541.html

cjava