Reputation: 23
I am working on a small program that requires me to read a set of parameters from a file, do some if else operations on them in 3 classes (all 3 classes inherit the same parent class). After each operation the method is supposed to print a line in an output file like this
output 1 of method 1 output 1 of method 2 output 2 of method 1 output 3 of method 1 etc
The idea is that all methods of all 3 classes should print in the same file, the order is unimportant.
I have used this code at the end of each method/if block
if/method {
.... do something
text ="output of something";
try(PrintWriter out = new PrintWriter("outputfile.txt") ){
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}//end if/method
The code does indeed write something to the file, however it always overwrites the previous line. So instead of having, for example, 12 lines of "something" I only have 1.
How can I fix this? I suspect it's because I make a new PrintWriter each time and have thought about declaring it somewhere else and calling it to each class. Would that work? How would I go about calling it to each class?
This is my first time working with files. Thank you.
Upvotes: 2
Views: 2086
Reputation: 3993
Constructor you are using to create a PrintWriter
uses new instance of FileOutputStream
internally.
The FileOutputStream
has two general write models:
Since you did not specify what mode to use, your writer will use the default. To tell it which mode you want, you will need to create FileOutputStream
with correct mode. For example, like this:
try(PrintWriter out = new PrintWriter(new FileOutputStream("outputfile.txt", true))) {
// note the boolean parameter in FileOS constructor above. Its "true" value means "Append"
out.println(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
There is something to be said about each class creating its own PrintWriter
as well:
I suggest that instead of each class creating its own output facility, it instead should receive one from outside:
class MyClass {
public void outputTo(PrintWriter w) {
String text = ...
w.println(text);
}
}
and you use it like this:
try (FileOutputStream fos = new FileOutputStream("filename", append);
PrintWriter w = new PrintWriter(fos)) {
new MyClass().outputTo(w); // first instance
new MyClass().outputTo(w); // second instance
//... etc.
}
Upvotes: 1
Reputation: 136
Try declaring the PrintWriter as a static variable of the parent class and use it in the subclasses as required.
Upvotes: 0