Search code examples
javaoutputstreamfileoutputstreamprintwriter

Java: PrintWriter not writing in file


I ran over some problem with PrintWriter. I wrote some code that simply takes some input from a file and outputs it to another one.

Though a file is created, the file remains empty. The wanted input can be easily printed out in the console, which means the FileInputStream is working correctly.

Why is PrintWriter not printing anything?

public static void writeInFile(File in, File out) throws FileNotFoundException {
    PrintWriter outputStream = null
    Scanner scanner = new Scanner(new FileInputStream(in));
    outputStream = new PrintWriter(new FileOutputStream(out));
    outputStream.print("test");
    while(scanner.hasNext()) {
    outputStream.print(scanner.nextLine() + "\n");
    }
    scanner.close();
}

Solution

  • Make sure you always close your OutputStreams:

            while(scanner.hasNext()) {
                String s = scanner.nextLine();
                outputStream.print(s+"\n");
                System.out.println("Test "+s); //d.h. das Problem liegt am outputstream
            }
            outputStream.close();
            scanner.close();
    

    Edit: When you close the outputStream it calls flush automatically, which writes the buffer to the file. Without closing it the buffer may never be emptied/written to the file, as was the case here.

    Also see this answer.