用Java写入文件。帮我编码

时间:2013-01-24 15:10:38

标签: java file-io filewriter

我正在传递一个文件路径到这个写入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) { }
}

5 个答案:

答案 0 :(得分: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编码约定。

答案 1 :(得分:1)

关闭你的PrintWriter,最后阻止循环

 finally {

         out.close();
    }

答案 2 :(得分:1)

最好使用Apache Commons IO。

http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html应该成功。

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

答案 3 :(得分: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);
            }
        }
}

答案 4 :(得分: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>