gpt4 book ai didi

java - 如何从控制台(包括错误和输出)重定向到 Java 文件?

转载 作者:行者123 更新时间:2023-11-29 03:15:02 24 4
gpt4 key购买 nike

package online_test;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class cmdline_test {
/**
* @param args
*/
public static void main(String[] args) {
try {
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/c";
command[2] = "c: && dir && cd snap";

Process p = Runtime.getRuntime().exec(command);

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Error;
while ((Error = stdError.readLine()) != null) {
System.out.println(Error);
}
while ((Error = stdInput.readLine()) != null) {
System.out.println(Error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

当我运行这段代码时,我将这段代码的输出打印到控制台。但是,我无法弄清楚如何将该输出复制到文件中。我将如何着手这样做?

最佳答案

使用 ProcessBuilder :

final File outputFile = Paths.get("somefile.txt").toFile();
final ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "whatever")
.redirectOutput(outputFile)
.redirectErrorStream(true);

final Process p = pb.start();
// etc

仔细阅读javadoc;您可以用它做很多事情(影响环境、更改工作目录等)。

此外,您真的需要通过翻译吗?

关于java - 如何从控制台(包括错误和输出)重定向到 Java 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27183369/

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