IO视频学习——Copy文本文件

来源:互联网 发布:c语言编译器好用的 编辑:程序博客网 时间:2024/05/20 07:51
import java.io.*;class CopyText_Ex01 {public static void main(String[] args) {//copyWay1();copyWay2();}public static void copyWay1(){FileWriter fw = null;FileReader fr = null;try{//创建文件写入流对象,若该文件在该目录下不存在;则新建该文件,否则覆盖。fw= new FileWriter("copy_txt.txt");//创建文件读取流对象,该文件是一定存在的fr = new FileReader("D:\\source.txt");//单个读取方式;int ch =0;while((ch=fr.read())!=-1){//写入单个字符fw.write(ch);}}catch(IOException e){System.out.println("catch:"+e.toString()+"\ncopy is failed");}finally{if(fr!=null)try{fr.close();}catch (IOException e){System.out.println("finally:"+e.toString());}if(fw!=null)try{fw.close();}catch (IOException e){System.out.println("finally:"+e.toString());}}}public static void copyWay2(){FileWriter fw = null;FileReader fr = null;try{//创建文件写入流对象,若该文件在该目录下存在;则新建该文件,否则在往该文件后追加数据,fw = new FileWriter("copy_txt.txt",true);//创建文件读取流对象,该文件是一定存在的fr = new FileReader("D:\\source.txt");//读取存到char[]数组中char[] buf = new char[1024];int num=0;while((num=fr.read(buf))!=-1){//写入字符串fw.write(new String(buf,0,num));}}catch(IOException e){System.out.println("catch:"+e.toString()+"\ncopy is failed");}finally{if(fr!=null)try{fr.close();}catch (IOException e){System.out.println("finally:"+e.toString());}if(fw!=null)try{fw.close();}catch (IOException e){System.out.println("finally:"+e.toString());}}}}

 
原创粉丝点击