题目:
编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下:
(1)使用FileInputStream、FileOutputStream和FileReader、FileWriter分别进行拷贝。
(2)使用字节流拷贝时,定义一个1024长度的字节数组作为缓冲区,使用字符流拷贝,使用BufferedReader和BufferedWriter包装流进行包装。
实现步骤:
①新建JavaProject
②在项目中新建一个FileCopy类
③打开项目的位置并新建begin1.txt(用于字节流拷贝文件)和begin2.txt(用于字符流拷贝文件)文件,并输入内容
④添加代码
源代码如下:
package ……;
import java.io.*;
public class FileCopy {
public static void main(String[] args) throws Exception{
//字节输入流,读
InputStream in = new FileInputStream("begin1.txt");
//字节输出流,写
OutputStream out = new FileOutputStream("end1.txt");
//定义一个1024长度的字节数组作为缓冲区
byte []buff = new byte[1024];
int len;
//获取开始时间
long begintime1 = System.currentTimeMillis();
while((len = in.read(buff)) != -1){
out.write(buff,0,len);
}
//获取结束时间
long endtime1 = System.currentTimeMillis();
System.out.println("拷贝所需要的时间为:"+(endtime1-begintime1)+"毫秒");
System.out.println("字节流拷贝文件已完成!");
in.close();
out.close();
//字符输入流,读
FileReader reader = new FileReader("begin2.txt");
//缓冲对象
BufferedReader br = new BufferedReader(reader);
//字符输出流,写
FileWriter writer = new FileWriter("end2.txt");
//缓冲对象
BufferedWriter bw = new BufferedWriter(writer);
String str;
//获取开始时间
long begintime2 = System.currentTimeMillis();
while((str = br.readLine()) != null) {
bw.write(str);
bw.newLine();
}
//获取结束时间
long endtime2 = System.currentTimeMillis();
System.out.println("拷贝所需要的时间为:"+(endtime2-begintime2)+"毫秒");
System.out.println("字符流拷贝文件已完成!");
br.close();
bw.close();
}
}