用FileInputStream和FileOutputStream拷贝文件

在E:\JavaIO中新建abc.txt文件,并在里面写上一些文字。现在要做的是,在Eclipse里面用FileInputStream和

FileOutputStream的read()和write()方法,实现,abc.txt文件的拷贝新建IOUitl.java,代码如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class IOUitl {
	public static void copyfile(File src,File des)throws IOException{
		if(!src.exists()){
			throw new IllegalArgumentException(src+"原文件不存在");
		}
		if(!src.isFile()){
			throw new IllegalArgumentException(src+"不是文件");
		}
		FileInputStream in = new FileInputStream(src);
		//文件不存在直接创建,文件存在删除后创建
		FileOutputStream out = new FileOutputStream(des);
		byte[] buf = new byte[8*1024];
		int b;
		//in.read(buf,0,buf.length)将读的数据存在buf数组,从0开始到数组长度
		while((b=in.read(buf,0,buf.length))!=-1){
			out.write(buf, 0, b);
			out.flush();
		}
		in.close();
	}
}

再定义一个Test.java的类进行测试:

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;

public class Test2  {
	public static void main(String[] args){
		File src = new File("E:\\JavaIO\\abc.txt");
		File des = new File("E:\\JavaIO\\abc1.txt");
			
	    try {
			IOUitl.copyfile(src, des);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

运行结果,打开文件目录,即可看到abc1.txt文件,里面内容和abc.txt一样,实现拷贝




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值