将已完成程序的结果(在控制台上)打印到文本文件?

时间:2018-09-05 23:07:22

标签: java file-io printwriter

我是Java的新手,因此,如果其中任何一个不清楚,我们深表歉意-我也想将控制台上的内容打印到文本文件中-但是我只希望它最后打印到文件中-所以基本上它将在所有程序中运行(这是一个猜谜游戏),然后一旦完成,它将要求用户输入文件名,然后将控制台上的内容打印到该文件。我对PrintWriter和BufferedWriter等有点熟悉,但是我不确定要打印出控制台上存在的结果(例如,问题是system.out.print和数字3、18)时该怎么做。 ,19是用户输入)。任何帮助将不胜感激!

  

请猜测1到20之间的数字:3

     

太低,请重试。请猜一个介于1到20之间的数字:18

     

太低,请重试。请猜一个介于1到20之间的数字:19

     

完美!

    System.out.println("Enter a file name: ");
    String fileName = Keyboard.readInput();

    File myFile = new File(fileName);

    try (PrintWriter pw = new PrintWriter(new FileWriter(fileName))) {
        pw.write(??????);
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

3 个答案:

答案 0 :(得分:2)

如果您希望创建一个系统来允许您使用System.out以便在打印到控制台的同时打印到文件,则可以为PrintStream创建包装器,以使其也写入到文件。 可以这样做:

public void setupLogger() {
    PrintStream stream=System.out;
    try {
        File file=new File(System.getProperty("user.dir")+"/log.txt");
        file.delete();
        file.createNewFile();
        System.setOut(new WrapperPrintStream(stream,file));
    } catch (IOException e) {
        e.printStackTrace();
    }

    for (int i = 0; i <100 ; i++) {
        System.out.println("Log test "+i);
    }


}
class WrapperPrintStream extends PrintStream{

    private PrintStream defaultOutput;

    public WrapperPrintStream(@NotNull PrintStream out, File file) throws FileNotFoundException {
        super(new PrintStream(new FileOutputStream(file),true), true);
        defaultOutput =out;

    }

    @Override
    public void println(String x) {
        super.println(x);
        defaultOutput.println(x);
    }

    @Override
    public void println() {
        super.println();
        defaultOutput.println();
    }
    //etc for all methods.
}

但是,我建议使用Log4J之类的API,它可以自动为您完成所有操作。

答案 1 :(得分:1)

已添加注释以澄清功能

package com.so.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Main {

    //Declare StringBuilder as global.
    private static StringBuilder systemOut = new StringBuilder();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //Instead of writing only to System.out only also write to a StringBuilder
        writeLnToStreams("Hello!");
        //Attempt to write to File
        try {
            FileOutputStream outputStream = new FileOutputStream(scanner.nextLine());
            outputStream.write(systemOut.toString().getBytes());
        } catch (IOException e) {
            //Will write only to System.err
            e.printStackTrace();
        }
    }

    /**
     *
     * @param output the output to write to System.out and the global StringBuilder
     */
    private static void writeToStreams(String output) {
        System.out.println(output);
        systemOut.append(output);
    }

    /**
     *
     * @param output the output to write to System.out and the global StringBuilder
     */
    private static void writeLnToStreams(String output) {
        System.out.println(output);
        systemOut.append(output).append("\n");
    }
}

答案 2 :(得分:0)

起初,我对这个问题不太了解,但我想我现在已经明白了。我的演示使用了输入和输出方法,类似于GurpusMaximus在他的回答(对他的+1)中显示的方法,但是我使用了不同的方法来获取输入和输出输出。

这是一个示例演示:

BufferedReader inputStream = null;
PrintWriter outputStream = null;
String writeString = "";

public void testMethod() {

    File file = new File("text.txt");

    try {
        inputStream = new BufferedReader(new InputStreamReader(System.in));
        outputStream = new PrintWriter(file);

        // Example console text
        println("Enter some text: ");
        String str = read();
        println("Entered: "+str);

        // Do this when you are done with the console and want to write to the file
        outputStream.print(writeString);
        inputStream.close();
        outputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

// Custom print method that also saves what was printed
public void println(String str) {
    System.out.println(str);
    writeString += str + System.lineSeparator(); // You can use the line separator call
                                                 // to format the text on different lines in
                                                 // the file, if you want that
}

// Custom read method that gets user input and also saves it
public String read() {
    try {
        String str = inputStream.readLine();
        writeString += str + System.lineSeparator();
        return str;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

让我知道这是否与您要寻找的东西更相关。