package com.starain.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteReadAndWrite {
public static void main(String[] args) throws IOException {
/*普通二进制读写完成copy文件方法,效率低*/
File filePathName1 = new File("D:/1.txt");
File filePathName2 = new File("e:/1.txt");
try {
FileInputStream file1 = new FileInputStream(filePathName1);
FileOutputStream file2 = new FileOutputStream(filePathName2);
byte put[] = new byte[12];
int count1 = 0;
while(file1.read(put)!=-1){
file2.write(put);
count1++;
}
System.out.println("读取"+count1+"次");
file1.close();
file2.close();
} catch (Exception e) {
System.out.println("error");
}
/*Buffered方法读写copy大文件*/
File filePathName3 = new File("E:/豆电雨/Struts2_值栈.wmv");
File filePathName4 = new File("f:\Struts2_值栈.wmv");
try {
FileInputStream file3 = new FileInputStream(filePathName3);
FileOutputStream file4 = new FileOutputStream(filePathName4);
BufferedInputStream bufferedFile1 = new BufferedInputStream(file3,1000000);//硬盘进制为1000,改变缓冲大小达到节省时间,优化读写的目的
BufferedOutputStream bufferedFile2 = new BufferedOutputStream(file4,1000000 );
byte []put2 = new byte[100000];
int count2 = 0;
long longTime1 = System.currentTimeMillis();
while(bufferedFile1.read(put2)!=-1){
bufferedFile2.write(put2);
count2++;
}
long longTime2 = System.currentTimeMillis();
System.out.println("用时:"+(longTime2 - longTime1)+"ms");
System.out.println("用"+count2+"次");
/*一定养成好的习惯,防止内存泄漏
*先创建的后关闭
*后创建的先关闭
*/
bufferedFile1.close();
bufferedFile2.close();
file3.close();
file4.close();
} catch (FileNotFoundException e) {
System.out.println("error2");
}
}
}