Question

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());
       }
   }
}
Était-ce utile?

La solution

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

Autres conseils

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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top