【发布时间】:2013-04-10 03:36:32
【问题描述】:
我对 Java NIO 很陌生,没有动手。关于 Java NIO,我知道它比 java.IO 快。
所以,为了尝试一下,我想到了编写简单的程序 “将一个文件的内容复制到另一个文件”。 "从大文件中搜索单词"。
同时使用 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);
}
使用蔚来
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() ;不能保证在一次调用中完成。
标签: java jakarta-ee io nio