gpt4 book ai didi

java - 将所有java输出写入txt文件中

转载 作者:行者123 更新时间:2023-12-01 09:07:42 29 4
gpt4 key购买 nike

我想知道如何将 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com