复制文件的雏形
public class MyTest2 {
public static void main(String[] args) throws IOException {
//采用读取一个字节,写入一个字节的方式,复制mp3文件
FileInputStream in = new FileInputStream("D:\\夜夜夜夜.mp3");
FileOutputStream out = new FileOutputStream("E:\\夜夜夜夜.mp3");
//int read = in.read();
//out.write(read);
int len = 0;
while ((len = in.read()) != -1) {
out.write(len);
}
in.close();
out.close();
}
}
发现问题进行优化:
很显然,一次读取一个字节,写一个字节,复制文件太耗时了,所以不推荐使用,我们推荐一次读取一个字节数组,写入一个字节数组。
public class MyTest3 {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("D:\\夜夜夜夜.mp3");
FileOutputStream out = new FileOutputStream("E:\\夜夜夜夜.mp3");
//创建一个字节数组,充当缓冲区
byte[] bytes = new byte[1024 * 8];
//定义一个变量,记录每次读取到的有效字节个数
int len = 0;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
in.close();
out.close();
}
}
进一步优化:
我们采用高效的字节流进行操作
public class MyTest {
public static void main(String[] args) throws IOException {
//高效的字节输入输出流
// BufferedInputStream
// BufferedOutputStream
// "D:\\夜夜夜夜.mp3"
//BufferedInputStream(InputStream in, int size)
//创建具有指定缓冲区大小的 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。
long start = System.currentTimeMillis();
//copyFile();
copyFile2();
long end = System.currentTimeMillis();
System.out.println("耗时" + (end - start) + "毫秒");
}
private static void copyFile2() throws IOException {
FileInputStream in = new FileInputStream("D:\\夜夜夜夜.mp3");
FileOutputStream out = new FileOutputStream("E:\\夜夜夜夜.mp3");
int len2 = 0;
byte[] bytes = new byte[1024 * 10];
while ((len2 = in.read(bytes)) != -1) {
out.write(bytes, 0, len2);
}
in.close();
out.close();
}
private static void copyFile() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\夜夜夜夜.mp3"), 1024 * 10);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\夜夜夜夜.mp3"), 1024 * 10);
int len2 = 0;
byte[] bytes = new byte[1024 * 10];
while ((len2 = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len2);
}
bis.close();
bos.close();
}
}