编写一个程序,分别使用字节流和字符流拷贝一个文本文件。(欢迎大家评论)

  1. 使用FileInputStreamFileOutputStreamFileReaderFileWriter分别进行拷贝。
  2. 使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区,使用字符流拷贝,使用BufferedReaderBufferedWriter包装流进行包装。
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为缓冲区,保留里面的字符内容

你可能感兴趣的:(Java)