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/tech/pnotes/10541.html