日期:2014-05-20  浏览次数:20756 次

有人能帮我看看这个程序么?读入一个文件到另外一个文件的方法!
public static void fileput(String filePath){
  int a = 0;
  FileReader fr = null;  
  FileWriter fw = null;
  try {
  fr = new FileReader(filePath);
  fw = new FileWriter("c:/javatest/cool.txt");
  while((a =fr.read()) != -1){
  fw.write(a);
  fr.close();
  fw.close();
  }
} catch (IOException e1) {  
System.out.println("就是错误!");
}
}


可以在指定位置创建文件,但是不能读入数据,请问为什么啊?

------解决方案--------------------
你流关闭的地方错了,应该读完了再写完了再关闭fr和fw。
不然你关了就没法写了。

Java code

    public static void fileput(String filePath) {
        int a = 0;
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader(filePath);
            fw = new FileWriter("c:/javatest/cool.txt");
            while ((a = fr.read()) != -1) {
                fw.write(a);
            }
        } catch (IOException e1) {
            System.out.println("就是错误!");
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }