未使用 缓冲字节流前
package file;
import java.io.*;
public class TestCopyBigFile {
public static void main(String[] args) {
long now = System.currentTimeMillis();
String srcFilePath = "测试包.rar";
String distFilePath = "/Users/hike/Desktop/java/JavaSE/aa/bb/cc/测试包.rar";
try(InputStream fis = new FileInputStream(srcFilePath); OutputStream fos = new FileOutputStream(distFilePath)){
// 单个字符写入实在太慢了
// int b;
// int index = 0;
// while ((b = fis.read()) != -1) {
// fos.write(b);
// index++;
// if (index % (1024*1024) == 0) {
// System.out.println("写入了 " + (index/ (1024*1024)) + "M...");
// }
// }
// 用字节数组的方式读取数据
byte[] bytes = new byte[1024];
int len;
int index = 0;
while((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
index++;
if (index % (1024) == 0) {
System.out.println("写入了 " + (index/ (1024)) + "M...");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("一共耗时 " + (System.currentTimeMillis() - now) + "毫秒");
}
}
使用缓冲字节流
package file;
import java.io.*;
public class TestCopyBigFile {
public static void main(String[] args) {
long now = System.currentTimeMillis();
String srcFilePath = "测试包.rar";
String distFilePath = "/Users/hike/Desktop/java/JavaSE/aa/bb/cc/测试包.rar";
// 就改了这一行代码
try(InputStream fis = new BufferedInputStream(new FileInputStream(srcFilePath)); OutputStream fos = new BufferedOutputStream(new FileOutputStream(distFilePath))){
// 用字节数组的方式读取数据
byte[] bytes = new byte[1024];
int len;
int index = 0;
while((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
index++;
if (index % (1024) == 0) {
System.out.println("写入了 " + (index/ (1024)) + "M...");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("一共耗时 " + (System.currentTimeMillis() - now) + "毫秒");
}
}