使用java NIO進行讀文件
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;
}
本文由用戶 n342 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!