简体   繁体   English

打印到系统和PrintWriter

[英]Printing to System and to PrintWriter

I have just over 100 lines of data and statistics that I need to print. 我有100多行需要打印的数据和统计信息。 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). 之所以要约100行,是因为我需要同时打印到系统和文件(每行约50行)。 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 使用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通过将其追加,在其中插入内容等来创建输出,一旦准备就绪,请将其打印到pSystem.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() 编写自己的println()

If you're using just the println() method, you could write your own method that calls it for both writers: 如果仅使用println()方法,则可以编写自己的方法来调用两个编写器:

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. 也就是说,假设p是一个字段,而不是局部变量。

Using format 使用格式

Instead of using println() you could use the printf() or format() methods. 除了使用println()还可以使用printf()format()方法。 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: 通过使用相同的格式字符串,您可以使用两个printf来保存许多println

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. 这会将以上三行输出打印到您的文件,然后打印到您的系统输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM