我想知道如何将 java 输出中的所有行写入 .txt 文件中。
到目前为止我已经做了一些测试,但我似乎无法找到解决方案:/
这是一个小代码,如果您能向我展示这个代码,我将不胜感激:
下面显示的代码询问用户在 .txt 文件中写入什么内容,但我希望它将所有打印行写入 .txt 文件中,而不询问用户任何内容。谢谢
package test;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Test {
public static void main(String[] args)throws Exception {
System.out.println("Hello");
System.out.println("Hi");
System.out.println("Hola");
System.out.println("Bonjour");
System.out.println("Hallo");
System.out.println("Hej");
System.out.println("Alo");
System.out.println("Ciao");
writeOutput();
}
public static void writeOutput() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromInput = in.readLine();
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
out.println(lineFromInput);
out.close();
}
}
最佳答案
直接使用PrintStream
写入String
值。
public static void main(String[] args)throws Exception {
PrintStream printStream = new PrintStream(new File("output.txt"));
// hook for closing the stream
Runtime.getRuntime().addShutdownHook(new Thread(printStream::close));
// writing
write(printStream,"Hello", "Hi", "Hola", "Bonjour", "Hallo", "Hej",
"Alo","Ciao");
// writing again
write(printStream, "A new String", "And again another one...");
}
public static void write(PrintStream printStream, String... values) throws Exception {
try{
for (String value : values){
printStream.println(value);
}
printStream.flush();
}
catch (Exception e){
// handling exception
}
}
}
关于java - 将所有java输出写入txt文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130712/