我正在学习一门操作系统课程,教授向我们展示了一些java进程管理的例子。这些例子是在linux操作系统上显示的,我正在尝试修改一些在windows中产生错误的代码。
下面的代码创建了一个进程,该进程列出目录中的文件,并且只用于理解父级和子级交互的一些机制。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class SimpleProcess1 {
public static void main(String[] args) throws InterruptedException, IOException {
ProcessBuilder pb = new ProcessBuilder("ls", "-la");
System.out.println("Run command");
Process process = pb.start();
while (process.isAlive()) {
System.out.println("The process is still runnning");
}
System.out.println("The process stopped. Any errors? " + (process.exitValue() == 0 ? "No" : "Yes"));
String text = new BufferedReader( new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)).lines().collect(Collectors.joining("\n"));
System.out.println("Echo Output:\n" + text);
}
}
我试图修改创建“ls”进程的代码行(在windows中不存在)
ProcessBuilder pb = new ProcessBuilder("dir");
但我在运行时遇到以下错误:
C:\java\Processi>java SimpleProcess1
Run command
Exception in thread "main" java.io.IOException: Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at SimpleProcess1.main(SimpleProcess1.java:13)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.base/java.lang.ProcessImpl.create(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 2 more
我应该如何修改命令?
暂无答案!
目前还没有任何答案,快来回答吧!