How do I use FileWriter to actually write into a file and then open it on notepad and see what I wrote? This is what I tried so far:

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());
       }
   }
}
有帮助吗?

解决方案

Don't forget to close your FileWriter once you are done writing to it.

其他提示

You should flush and close the PrintWriter like this:

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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top