文件复制!

今天看到文件的复制,就自己动手简单的写了一下!

1.通过FileInputStream 字节流实现:

@Test
	public void fileDemo() throws Exception {
		File file = new File("c:"+File.separator+"text.txt");		
		File filename=new File("c:"+File.separator+"textCopy.txt");
		if (filename.exists()) {
			filename.delete();
			filename.createNewFile();
			fileCopy(file,filename);
		} else {
			
			fileCopy(file,filename);
		}
	}
	public static void fileCopy(File file,File fileCopy) throws Exception{
		FileInputStream in = new FileInputStream(file);
		byte[] arr=new byte[in.available()];
		in.read(arr);
		FileOutputStream out =new FileOutputStream(fileCopy);
		out.write(arr);
		in.close();
		out.close();
	}

2.成行读取

@Test
	public void fileCopy() throws Exception {
		File file = new File("c:" + File.separator + "text.txt");
		File filename = new File("d:" + File.separator + "copy.txt");
		if (!filename.exists()) {
			filename.createNewFile();
		}
		copyDemo(file, filename);
	}

	public static void copyDemo(File file, File filename) throws Exception {
		BufferedReader bu = new BufferedReader(new FileReader(file));
		BufferedWriter wr = new BufferedWriter(new FileWriter(filename));
		String str = null;
		while ((str = bu.readLine()) != null) {
			wr.write(str);
			wr.newLine();
		}
		bu.close();
		wr.close();
	}

3.接收控制台输入的内容写到文件中

	@Test
	public void buffTest() throws IOException {
		InputStreamReader in = new InputStreamReader(System.in);
		BufferedReader bu = new BufferedReader(in);
		File file = new File("c:" + File.separator + "new.txt");
		BufferedWriter wr = new BufferedWriter(new FileWriter(file));
		String str = bu.readLine();
		System.out.println(str);
		wr.write(str);
		in.close();
		bu.close();
		wr.close();
	}


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值