我對Java NIO很陌生,沒有掌握它。關於Java NIO,我知道它是快速的,然後java.IO.IO和NIO性能差異和示例
所以,只是爲了試一試,我想爲 「複製一個文件的內容到另一個文件」編寫簡單的程序。 「從大文件搜索一個詞」。
同時使用java.io和java.nio包。
此外,我已分別在操作開始和結束之前和之後打印時間。
我沒有發現任何差異,因此NIO更快。可能是我走錯了方向。
任何人都可以請指導我通過場景,我可以通過示例正確看到區別?
編輯:
我真的很驚訝地知道,這個問題會得到反對票。 我剛纔提到我是NIO的新手,並且指導我如果走錯了方向。 我還沒有發佈程序,因爲它是非常基本的讀寫操作...請參見下面的程序我用來測試....
使用IO
public static void copyFile(File in, File out) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Before Read :"+strDate);
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
}
catch (Exception e) {
throw e;
}
finally {
if (fis != null) fis.close();
if (fos != null) fos.close();
}
Date now1 = new Date();
String strDate1 = sdf.format(now1);
System.out.println("After Read :"+strDate1);
}
使用NIO
public static void copyFile(File in, File out)
throws IOException
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println("Before Read :"+strDate);
FileChannel inChannel = new
FileInputStream(in).getChannel();
FileChannel outChannel = new
FileOutputStream(out).getChannel();
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
catch (IOException e) {
throw e;
}
finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
Date now1 = new Date();
String strDate1 = sdf.format(now1);
System.out.println("After Read :"+strDate1);
}
我從一個文件複製到另一個文件的文件大約爲20 MB。
爲什麼不顯示用於比較的代碼?也許有一個錯誤是放緩NIO版本。 –
您應該使用比1024更大的緩衝區。這些天的磁盤簇大小至少爲4096,並且不應低於此值。你必須在循環中調用transferTo();不保證在一次通話中完成。 – EJP