I have just over 100 lines of data and statistics that I need to print. I'm using:
PrintWriter p = new PrintWriter(fileName);
The reason why it's about 100 lines is because I need to print to both the System and the file (about 50 lines each). Is there any shorter way to print and "prettify" up my code?
System.out.println("Prints Stats"); //To System
p.println("Prints Stats"); //To File
etc
For every line printed to the System, there is an exact same line that is printed to the file. Is there a way to combine the two or to make it shorter? Or am I just stuck with this "ugly", long pile of prints?
There are several ways to do this.
Using a StringBuilder
If you are not writing tons of text, you could use a StringBuilder
to create your output by appending to it, inserting stuff inside it etc., and once it's ready, print it to both p
and System.out
.
StringBuilder b = new StringBuilder();
b.append("Name: ").append("Susan").append("\n");
// Append more stuff to b, also insert and delete from it if you want.
System.out.print(b);
p.print(b);
Writing your own println()
If you're using just the println()
method, you could write your own method that calls it for both writers:
private void println( String s ) {
System.out.println(s);
p.out.println(s);
}
That is, assuming p
is a field and not a local variable.
Using format
Instead of using println()
you could use the printf()
or format()
methods. The first parameter is a formatting string, and you can format several lines within one print using a format string. For example:
System.out.printf( "Name: %s%nSurname: %s%nAge: %d%n", "Susan", "Carter", 30 );
Would print
Name: Susan
Surname: Carter
Age: 30
And by using the same format string you can use two printf
s to save on many println
s:
String formatString = "Name: %s%nSurname: %s%nAge: %d%n";
Object[] arguments = { "Susan", "Carter", 30 );
p.printf( formatString, arguments );
System.out.printf( formatString, arguments );
This would print the above three-line output to your file and then to your System output.