IO流--拷贝文本文件

//将文本文件复制到当前目录。

/*
流式:
复制原理:
其实就是将文件数据存储到当前目录的一个文件中。

步骤:
1.在当前目录创建一个同名文件,用于存储文件中的数据。
2.定义读取流和原文件关联。
3.通过不断的读写完成数据存储。
4.关闭资源。
*/
import java.io.*;
class CopyText {
	public static void main(String[] args) {
		copy_1();
		copy_2();
	}

	//读一个字符,就写一个字符。
	public static void copy_1(){
		FileWriter fw = null;
		FileReader fr = null;
		try{
			//创建目的地
			fw = new FileWriter("RuntimeDemo_copy.java");

			//与已有文件关联
			fr = new FileReader("RuntimeDemo.java");
			
			int ch = 0;
			while((ch = fr.read()) != -1){
				fw.write(ch);
			}
		}
		catch (IOException e){
			throw new RuntimeException("读写失败!");
		}finally{
			try{
				if(fr != null)
					fr.close();
			}catch (IOException e){
				System.out.println(e.toString());
			}
			try{
				if(fw != null)
					fw.close();
			}catch (IOException e){
				System.out.println(e.toString());
			}
		}
	}

	//读完一块写。
	public static void copy_2(){
		FileWriter fw = null;
		FileReader fr = null;
		try{
			//创建目的地
			fw = new FileWriter("RuntimeDemo_copy.java");

			//与已有文件关联
			fr = new FileReader("RuntimeDemo.java");

			char[] buffer = new char[1024];
			
			int length = 0;
			while((length = read(buffer)) != -1){
				fw.write(buffer,0,length);
			}
		}catch (IOException e){
			throw new RuntimeException("读写失败!");
		}finally{
			try{
				if(fr != null)
					fr.close();
			}catch (IOException e){
				System.out.println(e.toString());
			}
			try{
				if(fw != null)
					fw.close();
			}catch (IOException e){
				System.out.println(e.toString());
			}
		}
	}
}
/*-----------------------------------------------------------------*/
/*
通过缓冲区复制一个.java文件。
readLine()方法返回的时候只返回回车符之前的数据内容,并不返回回车符。
*/
import java.io.*;
class CopyText {
	public static void main(String[] args) {
		copy_1();
	}

	//读一个字符,就写一个字符。
	public static void copy_1(){
		BufferedReader br = null;
		BufferedWriter bw = null;
		try{
			//创建缓冲区
			br = new BufferedReader(new FileReader("RuntimeDemo.java"));

			bw = new BufferedWriter(new FileWriter("RuntimeDemo.java"));
			
			String line = null;
			while((line = br.readLine()) != null){
				bw.write(line);
				bw.newLine();
				bw.flush();
			}
		}catch (IOException e){
			throw new RuntimeException("读写失败!");
		}finally
		{
			try{
				if(br != null)
					br.close();
			}catch (IOException e){
				System.out.println(e.toString());
			}try{
				if(bw != null)
					bw.close();
			}catch (IOException e){
				System.out.println(e.toString());
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值