使用Java的IO与NIO来Copy文件的四种方法实现以及性能对比
FileCopyRunner接口,定义了Copy文件的接口,等下在测试类中使用匿名内部类来实现。
package nio.channel;
import java.io.File;
public interface FileCopyRunner {
void copyFile(File source , File target);
}
测试类:
benchmark()
:Copy文件ROUNDS(5)
次,并且返回耗费的平均时间(1.0F)*elapsed / ROUNDS
。close()
:关闭资源。
完整代码(下面说四种方法):
package nio.channel;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileCopyDemo {
private static final int ROUNDS = 5;
private static void benchmark(FileCopyRunner test ,
File sourse , File target){
long elapsed = 0L;
for (int i = 0; i < ROUNDS; i++) {
long startTime = System.currentTimeMillis();
test.copyFile(sourse , target);
elapsed += System.currentTimeMillis() - startTime;
target.delete();
}
System.out.println(test+":"+(1.0F)*elapsed / ROUNDS);
}
public static void close(Closeable closeable){
if(closeable != null){
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
FileCopyRunner noBufferStreamCopy = new FileCopyRunner() {
@Override
public void copyFile(File sourse, File target) {
InputStream fin = null;
OutputStream fout = null;
try {
fin = new FileInputStream(sourse);
fout = new FileOutputStream(target);
int result;
while((result = fin.read()) != -1){
fout.write(result);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
close(fin);
close(fout);
}
}
@Override
public String toString() {
return "noBufferStreamCopy";
}
};
FileCopyRunner bufferedStreamCopy = new FileCopyRunner() {
@Override
public void copyFile(File sourse, File target) {
InputStream fin = null;
OutputStream fout = null;
try {
fin = new BufferedInputStream(new FileInputStream(sourse));
fout = new BufferedOutputStream(new FileOutputStream(target));
byte[] buffer = new byte[8192];
int result;
while((result = fin.read(buffer)) != -1){
fout.write(buffer , 0 ,result);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
close(fin);
close(fout);
}
}
@Override
publ