使用Java的NIO(new io)一定快么?(需要有io的相关基础知识!)
不一定,要看以流的方式代码怎么写,直接上代码(使用nio复制文件是随便在网上找的代码)
public static void main(String[] args) {
//txt存储了1个G的文字
init();
}
public static void init(){
long start=System.currentTimeMillis();
System.out.println("start:"+start);
fileCopyWithFileChannel(new File("D:\1.txt"),new File("D:\in\1.txt"));
long end = System.currentTimeMillis();
System.out.println("end:"+end);
System.out.println("end-start:"+(end-start));
System.out.println("---------------------");
long start2=System.currentTimeMillis();
System.out.println("start2:"+start2);
copyFileUsingStream(new File("D:\2.txt"),new File("D:\in\2.txt"));
long end2 = System.currentTimeMillis();
System.out.println("end2:"+end2);
System.out.println("end-start:"+(end2-start2));
}
public static void fileCopyWithFileChannel(File fromFile, File toFile) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
FileChannel fileChannelInput = null;
FileChannel fileChannelOutput = null;
try {
fileInputStream = new FileInputStream(fromFile);
fileOutputStream = new FileOutputStream(toFile);
//得到fileInputStream的文件通道
fileChannelInput = fileInputStream.getChannel();
//得到fileOutputStream的文件通道
fileChannelOutput = fileOutputStream.getChannel();
//将fileChannelInput通道的数据,写入到fileChannelOutput通道
fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null)
fileInputStream.close();
if (fileChannelInput != null)
fileChannelInput.close();
if (fileOutputStream != null)
fileOutputStream.close();
if (fileChannelOutput != null)
fileChannelOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void copyFileUsingStream(File source, File dest) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
// 1024会慢10倍
// byte[] buffer = new byte[1024];
// 102400会快很多
byte[] buffer = new byte[102400];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
}catch (Exception e){
e.printStackTrace();
} finally {
try{
is.close();
os.close();
}catch (Exception e){
e.printStackTrace();
}
}
}