import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 分享一下
* 需求:复制MP3.
* 分析:MP3是二进制数据,所以只能只用字节流。而字节流有四种方案。
*
* 方案1:基本流一次读取一个字节 42812毫秒
* 方案2:基本流一次读取一个字节数组 47毫秒
* 方案3:缓冲流一次读取一个字节 500毫秒
* 方案4:缓冲流一次读取一个字节数组 15毫秒
*
* 测试每一种功能的时间。
*/
public class CopyMP3 {
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
//method1();
//method2();
//method3();
method4();
long end = System.currentTimeMillis();
System.out.println((end - start) + "毫秒");
}
// 方式1
public static void method1() throws IOException {
FileInputStream fis = new FileInputStream("d:\\zxmzf.mp3");
FileOutputStream fos = new FileOutputStream("copy1.mp3");
int by = 0;
while ((by = fis.read()) != -1) {
fos.write(by);
}
fos.close();
fis.close();
}
// 方式2
public static void method2() throws IOException {
FileInputStream fis = new FileInputStream("d:\\zxmzf.mp3");
FileOutputStream fos = new FileOutputStream("copy2.mp3");
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fos.close();
fis.close();
}
// 方式3
public static void method3() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
"d:\\zxmzf.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("copy3.mp3"));
int by = 0;
while ((by = bis.read()) != -1) {
bos.write(by);
}
bos.close();
bis.close();
}
// 方式4
public static void method4() throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
"d:\\zxmzf.mp3"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("copy4.mp3"));
byte[] bys = new byte[1024];
int len = 0;
while ((len = bis.read(bys)) != -1) {
bos.write(bys, 0, len);
}
bos.close();
bis.close();
}
}
|