java---编写一个程序,分别使用字节流和字符流拷贝一个文本文件。

题目:
编写一个程序,分别使用字节流和字符流拷贝一个文本文件。要求如下:
(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();
	}

}
  • 12
    点赞
  • 71
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值