Question: 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();
}

```

Answer: 
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](https://stackoverflow.com/a/2340125/3927528).
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);
    }
}

```