0

I am trying to create and write to a java file using print writer.
I looked at How do I create a file and write to it in Java? I am unable to write to the file. The file is created but with no text Can someone please tell me what I missed?
Thanks

static void createFile() throws FileNotFoundException{
    String filename = "nothign.txt";
    FileOutputStream connection1;
    connection1 = new FileOutputStream( filename );
    PrintWriter printnothing = null;

    printnothing = new PrintWriter(connection1);
    printnothing.printf("/nnewline writesomething/n exo");
    printnothing.println("trying to write something");
}// createFile Method
Community
  • 1
  • 1
H J
  • 369
  • 2
  • 6
  • 10

3 Answers3

4

I believe you need to close your PrintWriter in order to flush the contents to the file. Try adding this to the end of your code:

printnothing.close();
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

You have to flush.

  1. You can automatically flush if you supply true as second parameter in the constructor.
  2. You can flush manually by calling flush().
  3. You can flush implicitly by closing the stream with .close().

You also need to close the stream so the file is released.

  1. You can do it with explicitly calling .close() when you're done with it.
  2. You can take advantage of Java 7's try-with-resource feature with the following syntax..

Example:

try (PrintWriter printnothing = new PrintWriter(new FileOutputStream("nothign.txt"))) {
     printnothing.printf("stuff"); 
     printnothing.println("stuff");
} catch(IOException e) { 
     e.printStacktrace(); // We don't have to close it here, and neither do have to in a finally block - it's handled for us 
}
Xabster
  • 3,710
  • 15
  • 21
0

You need to call either printnothig.close() (which is what you should do assuming you won't be using that object to print again) or printnothing.flush()

Caleb Brinkman
  • 2,489
  • 3
  • 26
  • 40