IO—纯文本复制

用输入、输出字符流实现纯文本复制

/**
 * 字符输入、输出流实现纯文本复制
 */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class CopyTxt {
public static void main(String[] args) {
		
//		Scanner in=new Scanner(System.in);
//		
//		String msg=in.nextLine();
		//1、选择源
		File src=new File("abc.txt");
		File dest=new File("dest.txt");
		//2、选择流
		Reader is=null;
		Writer os=null;
		try {
			is=new  FileReader(src);
			os=new FileWriter(dest,true);
			//3、操作
			char[] flush=new char[1024];//缓冲容器
			int len=-1;
			while((len=is.read(flush))!=-1) {//read返回的是缓存容器中存储字节的个数
				//写入目标文件
				os.write(flush,0,len);
				os.flush();//刷新,防止驻留在缓存
			}	
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			//4、释放资源 先打开的后关闭
			if(null!=os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if(null!=is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
					}
				}
			}
		}
	}
}

posted @ 2022-04-08 23:24  FireCode  阅读(58)  评论(0)    收藏  举报