我正在开发需要模拟以下内容的java代码:
my_command < file.txt
我测试了写入 STDIN,但这似乎不是解决方案。
有人已经开发出来了吗?
注意,在下面的代码中,
source
是 java.io.File
String commandLine = "myCommand";
Process process = Runtime.getRuntime().exec(commandLine);
new Thread(() -> {
try (BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
Scanner scanner = new Scanner(source)
){
String line;
while (scanner.hasNext()) {
line = scanner.nextLine();
stdin.write(line);
System.out.print(line);
}
stdin.flush();
} catch (IOException e) {
e.printStackTrace();
}
}).start();
int ret = process.waitFor();
仅供引用,我的命令是mysql
最佳答案
您应该使用类 ProcessBuilder (而不是类Runtime
)。
我不知道你的my_command是什么,所以下面的代码使用cleartool .
首先,我创建包含我希望执行的 cleartool 子命令的文本文件。
hostinfo
exit
(请注意文件的最后一行为空。)
我将此文件命名为 exits_ct.txt
现在的 java 代码将运行 cleartool 命令,然后从文本文件输入子命令并将命令输出打印到标准输出。
import java.io.File;
import java.io.IOException;
public class PrcBldTs {
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("cleartool");
pb.redirectInput(new File("exits_ct.txt"));
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
pb.redirectError(ProcessBuilder.Redirect.INHERIT);
try {
Process proc = pb.start(); // throws java.io.IOException
int result = proc.waitFor(); // throws java.lang.InterruptedException
System.out.println("result: " + result);
}
catch (IOException | InterruptedException x) {
x.printStackTrace();
}
}
}
当我运行上面的代码时,我得到以下输出:
MY_COMP: ClearCase 9.0.0.0 (Windows NT 6.2 (build 9200) Pentium)
result: 0
关于java - 如何编写代码来模拟命令< file.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67921018/