Skip to content
Advertisement

Java PrintStream .println() method not outputting to file?

I am trying to write a method which recursively gathers data from files, and writes erroneous data to an error file. See code block:

JavaScript

However, the error file is always blank.

I’ve tried calling the .flush() and .close() methods. System.err is outputting so I know the code is being run. I’ve tried instantiating the PrintStream outside of the try-with-resources, no change.

I’ve tried calling the method at earlier points in the code (i.e. right after instantiation of the printStream, and in the if{} block) and it does output to the error file. It’s only within the catch{} and else{} blocks (where I actually need it to work) that it refuses to print anything. I’ve also tried storing the error data and using a loop after the blocks to print the data and it still won’t work. See code block:

JavaScript

Edit

Code has been edited to show instantiation of the PrintStream only once. The error persists. I am sorry there is no Repex, I cannot recreate this error except for in this specific case.

Advertisement

Answer

I have solved the issue. I’m not really sure what the issue was, but it appears to have something to do with the PrintStream being instantiated in a method other than the main{} method. This would also explain why I was unable to recreate this error, try as I might.

As such, I’ve solved it by simply storing the errors in a list and printing them in the main{} method.

JavaScript

This has the downside of taking up more memory, but I see no other way to get this to work the way I want it to. Thanks for the help!

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement