我对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