- 简单写法?(一次只读一个字节,耗时长)
import java.io.*;
import java.nio.file.Path;
public class Test {
public static void main(String[] args) throws IOException {
String sourcePath = "C:\\Users\\Lenovo\\Desktop\\栈帧.png";
String destPath = "C:\\Users\\Lenovo\\Desktop\\栈帧2.png";
copyFile(sourcePath,destPath);
}
public static boolean copyFile(String sourcePath, String destPath) throws IOException{
//1.取得File对象
File sourceFile = new File(sourcePath);
File destFile = new File(destPath);
//2.取得输入输出流
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
//3.数据的输入输出
long start = System.currentTimeMillis();
//一次只读一个字节
int len = 0;
while((len = in.read()) != -1){
out.write(len);
}
long end = System.currentTimeMillis();
System.out.println("文件拷贝共耗时:"+(end-start)+"ms");
return true;
}
}
显示结果:
- 改进写法?:一次只读一个字节太慢了。。。可以引入缓冲区
public static boolean copyFile(String sourcePath, String destPath) throws IOException{
//1.取得File对象
File sourceFile = new File(sourcePath);
File destFile = new File(destPath);
//2.取得输入输出流
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
//3.数据的输入输出
long start = System.currentTimeMillis();
//引入缓冲区
int len = 0;
byte[] buffer = new byte[1024];
while((len = in.read(buffer)) != -1){
out.write(buffer,0,len);
}
long end = System.currentTimeMillis();
System.out.println("文件拷贝共耗时:"+(end-start)+"ms");
return true;
}
}
显示结果:
相比而言,后者拷贝速度上有了很大提升