FileWriter写入文件

时间:2014-02-14 13:44:06

标签: java java-io filewriter

如何使用FileWriter实际写入文件,然后在记事本上打开它,看看我写了什么?这是我到目前为止所尝试的:

package Experimental;

import java.io.*;

public class IO {

    public static void main (String args[]) {

       File f = new File("testFile.txt");

       //Outputting into a file
       try {

          PrintWriter filePrint = new PrintWriter(
             new BufferedWriter(new FileWriter(f,true))
          );
          filePrint.println("testing, testing, printing into a file (apparently)");
       } catch (IOException e) {
          System.out.println(e.getMessage());
       }
   }
}

2 个答案:

答案 0 :(得分:7)

完成写作后,请不要忘记close FileWriter

答案 1 :(得分:0)

您应该刷新关闭 PrintWriter,如下所示:

File file = new File("testFile.txt");
PrintWriter filePrint = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));

try 
{
  try 
  {
    filePrint.println("testing, testing, printing into a file (apparently)");
    filePrint.flush();
  } 
  finally
  {
    filePrint.close();
  }
}
catch (IOException e) 
{
  e.printStackTrace();
}