使用 FileInputStream 、 FileOutputStream 和 FileReader 、 FileWriter 分别进行拷贝。 使用字节流拷贝时,定义一个 1024 长度的字节数组作为缓冲区,使用字符流拷贝,使用 BufferedReader 和 BufferedWriter 包装流进行包装。
import java.io.*;
public class Fuzhi {
public static void main(String[] args)throws Exception{
FileInputStream in=new FileInputStream("D:/HelloWorld.txt");
FileOutputStream out=new FileOutputStream("D:/Hello.txt");
byte[] buff=new byte[1024];
int len;
long begintime=System.currentTimeMillis();
while((len=in.read(buff))!=-1){
//System.out.write(len);
out.write(buff,0,len);
}
long endtime=System.currentTimeMillis();
System.out.println("拷贝文件所消耗的时间是:"+(endtime-begintime)+"毫秒");
in.close();
out.close();
BufferedReader br=new BufferedReader(new FileReader("D:/HelloChina.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("D:/China.txt"));
String str;
long starttime=System.currentTimeMillis();
while((str=br.readLine())!=null){
bw.write(str);
bw.newLine();
}
long overtime=System.currentTimeMillis();
System.out.println("拷贝文件所消耗的时间是:"+(overtime-starttime)+"毫秒");
br.close();
bw.close();
}
}
使用字节流时,判断是否为最后一行时必须代入buff,因为buff为缓冲区,保留里面的字符内容