0

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();
}
kaiya
  • 271
  • 1
  • 3
  • 16
  • 4
    Looks like you never close the outputStream in the second method. – 17slim Jun 20 '18 at 18:18
  • you probably want to check `scanner.hasNextLine()` in writeIntFile instead of `scanner.hasNext()` since you are grabbing line by line with `scanner.nextLine()` – RAZ_Muh_Taz Jun 20 '18 at 18:19

2 Answers2

2

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.

17slim
  • 1,233
  • 1
  • 16
  • 21
0

When dealing with IO which requires cleanup, I prefer to use auto resource cleanup. This is all you need at the most basic level:

public static void writeInToOut(InputStream in, OutputStream out) {
    try(PrintWriter outputStream = new PrintWriter(out);
        Scanner scanner = new Scanner(in)) {
        while(scanner.hasNext()) {
            outputStream.print(scanner.nextLine()+"\n");
        }
    }
}

You can now overload this function in several ways:

public static void writeInToOut(File file, OutputStream out) {
    try (InputStream in = new FileInputStream(file)) {
        writeInToOut(in, out);
    } catch (IOException e) {
        Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
    }
}

public static void writeInToOut(File inFile, File outFile) {
    try (InputStream in = new FileInputStream(inFile);
         OutputStream out = new FileOutputStream(outFile)) {
        writeInToOut(in, out);
    } catch (IOException e) {
        Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
    }
}

public static void writeStdInToFile(File file) {
    try (OutputStream out = new FileOutputStream(file)) {
        writeInToOut(System.in, out);
    } catch (IOException e) {
        Logger.getAnonymousLogger().log(Level.WARNING, "IOError", e);
    }
}
smac89
  • 39,374
  • 15
  • 132
  • 179