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

问题描述 投票:1回答:3

我是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());
    }
java file-io printwriter
3个回答
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
投票

添加了评论以澄清功能

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");
    }
}

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;
}

如果这与您正在寻找的内容更相关,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.