1

我将文件路径传递给此方法,该方法写入 in txt 文件。但是当我运行这个程序时,它并没有写满,我不知道我在哪里犯了错误。

public void content(String s) {
  try { 
    BufferedReader br=new BufferedReader(new FileReader(s)); 
    try {
      String read=s;
      while((read = br.readLine()) != null) {    
        PrintWriter out = new PrintWriter(new FileWriter("e:\\OP.txt"));
        out.write(read);
        out.close();
      }
    } catch(Exception e) { }    
  } catch(Exception e) { }
}
4

5 回答 5

7

您不应该每次都在循环内创建 PrintWriter:

public void content(String s) {
   BufferedReader br=new BufferedReader(new FileReader(s));

   try {
      PrintWriter out=new PrintWriter(new FileWriter("e:\\OP.txt"));
      String read=null;

      while((read=br.readLine())!=null) {
         out.write(read);
      }
   } catch(Exception e) {
      //do something meaningfull}
   } finally {
      out.close();
   }
}

此外,正如其他人提到的那样,添加一个 finally 块,不要默默地捕获异常,并遵循 Java 编码约定。

于 2013-01-24T15:15:37.187 回答
1

关闭你的 PrintWriter 最终阻止循环

 finally {

         out.close();
    }
于 2013-01-24T15:11:41.367 回答
1

最好改用 Apache Commons IO。

http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html应该可以解决问题。

(除非您正在尝试学习低级的东西,或者实际上知道为什么不能在这种情况下使用 IOUtils。)

于 2013-01-24T15:18:23.577 回答
0

试试这个

public void content(String s) throws IOException { 
        try (BufferedReader br = new BufferedReader(new FileReader(s));
                PrintWriter pr = new PrintWriter(new File("e:\\OP.txt"))) {
            for (String line; (line = br.readLine()) != null;) {
                pr.println(line);
            }
        }
}
于 2013-01-24T15:18:06.457 回答
0

在完成之前关闭流。所以要么把它放进去

<code>
finally {
out.close();
}
</code>

or see this simple example

<code>try {
    String content = s;
    File file = new File("/filename.txt");

    // if file doesnt exists, then create it
    if (!file.exists()) {
    file.createNewFile();
    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();
    System.out.println("Done");
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
</code>
于 2013-01-24T15:28:42.090 回答