- package cn.javastudy.p10.io.demo;
- import java.io.*;
- /*
- * 读取源文件
- * 把读取的源文件写到目标文件
- */
- public class CopyExpression {
- public static void main(String[] args) {
- copyData("d:\\demo.txt","E:\\demo.txt");
- }
- public static void copyData(String res, String des) {
- FileReader fr=null;
- BufferedReader bfr=null;
- FileWriter fw=null;
- BufferedWriter bfw=null;
- try {
- fr=new FileReader("D:\\demo.txt");
- fw=new FileWriter("E:\\demo.txt");
- bfr=new BufferedReader(fr);
- bfw=new BufferedWriter(fw);
- String line=null;
- while((line=bfr.readLine())!=null)
- {
- bfw.write(line);
- bfw.newLine();
- bfw.flush();
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- System.out.println(e.getMessage());
- } catch (IOException e) {
- // TODO Auto-generated catch block
- System.out.println(e.getMessage());
- }finally{
- if(fr!=null)
- try {
- fr.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- System.out.println(e.getMessage());
- }
- if(fw!=null)
- try {
- fw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- System.out.println(e.getMessage());
- }
- }
-
-
- }
- }
复制代码 /*
在此实例中为什么不调用字符缓冲区的关闭,而是调用字符流对象FileReader和FileWriter对象的关闭,是因为,有可能这两个对象在创建时发生异常,倒至下面的BufferedReader和BufferedWriter对象没法如始化,如果调用了字符缓冲区的关闭时,有可能发生PrinterException异常,再有的就是字符缓冲区的BufferedReader和BufferedWriter的Close方法调用的也底层的关闭.因此在这个程序中调用底层的关闭比较合适.
*/ |