将已完成程序(在控制台上)的结果打印到文本文件?
Printing the results of a completed program (on the console) to a text file?
我是 Java 的新手,如果有任何不清楚的地方,我深表歉意 - 我也想将控制台上的内容打印到文本文件中 - 但我只希望它打印到文件在最后 - 所以基本上它会 运行 通过所有程序(这是一个猜谜游戏),然后一旦完成,它会要求用户输入文件名,然后将控制台上的内容打印到那个文件。我对 PrintWriter 和 BufferedWriter 等有点熟悉,但是当我想打印出控制台上存在的结果时,我不确定该怎么做,如下所示(问题是 system.out.print 和数字 3、18 , 19 是用户输入)。任何帮助将不胜感激!
Please guess a number between 1 and 20: 3
Too low, try again. Please guess a number between 1 and 20: 18
Too low, try again. Please guess a number between 1 and 20: 19
Perfect!
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());
}
已添加注释以澄清功能
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");
}
}
如果您希望创建一个允许您使用 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,它会自动为您完成这一切。
起初我不太理解这个问题,但我想我现在明白了。我的演示使用输入和输出方法,类似于 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;
}
如果这与您正在寻找的内容更相关,请告诉我。
我是 Java 的新手,如果有任何不清楚的地方,我深表歉意 - 我也想将控制台上的内容打印到文本文件中 - 但我只希望它打印到文件在最后 - 所以基本上它会 运行 通过所有程序(这是一个猜谜游戏),然后一旦完成,它会要求用户输入文件名,然后将控制台上的内容打印到那个文件。我对 PrintWriter 和 BufferedWriter 等有点熟悉,但是当我想打印出控制台上存在的结果时,我不确定该怎么做,如下所示(问题是 system.out.print 和数字 3、18 , 19 是用户输入)。任何帮助将不胜感激!
Please guess a number between 1 and 20: 3
Too low, try again. Please guess a number between 1 and 20: 18
Too low, try again. Please guess a number between 1 and 20: 19
Perfect!
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());
}
已添加注释以澄清功能
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");
}
}
如果您希望创建一个允许您使用 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,它会自动为您完成这一切。
起初我不太理解这个问题,但我想我现在明白了。我的演示使用输入和输出方法,类似于 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;
}
如果这与您正在寻找的内容更相关,请告诉我。