将java输出写入控制台和文本文件的更简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19107853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:09:35  来源:igfitidea点击:

Simpler way to write a java output to both console and text file?

javafilefilewriter

提问by DarkD

So im a pretty big noob at java and I have a exam coming up and have been practicing all week. My progress has been slow but steady. One exercise I am doing requires me to print the output of an array calculation to a console AND create a file temperature.txtwith the console output and same formatting.

所以我是一个非常大的 Java 菜鸟,我要考试了,我整个星期都在练习。我的进步缓慢但稳定。我正在做的一个练习要求我将数组计算的输出打印到控制台并创建一个temperature.txt具有控制台输出和相同格式的文件。

I've figured out how to be able to do one or the other but i'm having trouble doing both (remember slow and steady learner). Is there a simpler beginners method to keep in mind?

我已经想出了如何能够做到其中之一,但我在同时做这件事时遇到了麻烦(记住缓慢而稳定的学习者)。有没有更简单的初学者方法要记住?

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;

public class Temperature {

    public static void main(String[] args) throws IOException{ 
        double[] temps = {100, 98, 80.5, 90.2, 99.4, 89.1};
        MaxMin(temps);

    }

    public static void MaxMin(double[]temps) throws IOException{
        FileWriter fwriter = new FileWriter("Temperatures.txt", true);
        PrintWriter outputfile = new PrintWriter(fwriter);
        double min= Double.MAX_VALUE;
        double max= Double.MIN_VALUE;
        double sum = 0;

        DecimalFormat formatter = new DecimalFormat("0.0");

        for(int i = 0;i<temps.length;i++){
            sum += temps[i];
            if(temps[i] > max){
                max = temps[i];
            }
            if(temps[i]< min){
                min = temps[i];
            }
        }

        double avg = sum / temps.length;
        outputfile.println("Average Temp: " + formatter.format(avg));
        outputfile.println("Maximum Temp: " + formatter.format(max));
        outputfile.println("Minimum Temp: " + formatter.format(min));
        outputfile.close();
    }
}

What I have above prints the text but nothing on the console.

我上面的内容打印了文本,但在控制台上什么也没有。

edit: would it be acceptable to just add 3 System.out.println statements at the end to fulfill both requirements? like this:

编辑:在最后添加 3 个 System.out.println 语句来满足这两个要求是否可以接受?像这样:

System.out.println("Average Temp: " + formatter.format(avg));
System.out.println("Maximum Temp: " + formatter.format(max));
System.out.println("Minimum Temp: " + formatter.format(min));

outputfile.println("Average Temp: " + formatter.format(avg));
outputfile.println("Maximum Temp: " + formatter.format(max));
outputfile.println("Minimum Temp: " + formatter.format(min));
outputfile.close();

回答by nhgrif

First of all, if it's important that the formatting be identical between console and file, then I'd save all of your output to a single String, embedding the '\n'characters and such, and then just print/write that Stringall in one go.

首先,如果控制台和文件之间的格式相同很重要,那么我会将您的所有输出保存到单个String,嵌入'\n'字符等,然后String一次性打印/写入所有内容。

I don't know off hand whether or not there's a method for writing to both file and console at the same time. You can always write a function that will do both of these things though.

我不知道是否有一种方法可以同时写入文件和控制台。不过,您始终可以编写一个可以同时完成这两件事的函数。

回答by Thilo

Commons IO has a TeeOutputStreamthat writes everything to two outputs at once.

Commons IO 有一个TeeOutputStream,可以一次将所有内容写入两个输出。

回答by Digital Alchemist

Log4jis a Reliable, Fast and Flexible Logging Framework for console and file appending.

Log4j是一个可靠、快速和灵活的日志框架,用于控制台和文件附加。

Logging Exampleto append on Console and File togather!

在控制台和文件上附加的日志示例

回答by YAMM

    public static void MaxMin(double[] temps) throws IOException {
    FileWriter fwriter = new FileWriter("Temperatures.txt", true);
    PrintWriter outputfile = new PrintWriter(fwriter);
    double min = Double.MAX_VALUE;
    double max = Double.MIN_VALUE;
    double sum = 0;

    DecimalFormat formatter = new DecimalFormat("0.0");

    for (int i = 0; i < temps.length; i++) {
        sum += temps[i];
        if (temps[i] > max) {
            max = temps[i];
        }
        if (temps[i] < min) {
            min = temps[i];
        }
    }
    double avg = sum / temps.length;



    String str = "Average Temp: " + formatter.format(avg) + "\n"
            + "Maximum Temp: " + formatter.format(max) + "\n"
            + "Minimum Temp: " + formatter.format(min);
    System.out.println(str);
    outputfile.println(str);
    outputfile.close();

}

make a string and then print it twice, \nis a linebreak

制作一个字符串然后打印两次,\n是换行符

回答by epoch

The simplest in your case would be to create an outputmethod:

在您的情况下,最简单的output方法是创建一个方法:

private void output(final String msg, PrintStream out1, PrintWriter out2) {        
    out1.println(msg);
    out2.println(msg);
}

And using it like this:

并像这样使用它:

output("your message", System.out, outputfile);