在 Java 中启动进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3774432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Starting a process in Java?
提问by jmasterx
Is there a way to start a process in Java? in .Net this is done with for example:
有没有办法用Java启动进程?在 .Net 中,这是通过例如:
System.Diagnostics.Process.Start("processname");
Is there an equivalent in Java so I can then let the user find the application and then it would work for any OS?
Java 中是否有等价物,以便我可以让用户找到该应用程序,然后它可以在任何操作系统上使用?
采纳答案by James P.
http://www.rgagnon.com/javadetails/java-0014.html
http://www.rgagnon.com/javadetails/java-0014.html
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Paths;
public class CmdExec {
public static void main(String args[]) {
try {
// enter code here
Process p = Runtime.getRuntime().exec(
Paths.get(System.getenv("windir"), "system32", "tree.com /A").toString()
);
// enter code here
try(BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
} catch (Exception err) {
err.printStackTrace();
}
}
}
You can get the local path using System properties or a similar approach.
您可以使用系统属性或类似方法获取本地路径。
http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html
http://download.oracle.com/javase/tutorial/essential/environment/sysprop.html
回答by NullUserException
See Runtime.exec()
and the Process
class. In its simplest form:
见Runtime.exec()
和Process
类。以其最简单的形式:
Process myProcess = Runtime.getRuntime().exec(command);
...
Note that you also need to read the process' output (eg: myProcess.getInputStream()
) -- or the process will hang on some systems. This can be highly confusing the first time, and should be included in any introduction to these APIs. See James P.'s response for an example.
请注意,您还需要读取进程的输出(例如:myProcess.getInputStream()
)——否则该进程将在某些系统上挂起。这在第一次使用时可能会非常混乱,并且应该包含在对这些 API 的任何介绍中。参见 James P. 的回应示例。
You might also want to look into the new ProcessBuilder
class, which makes it easier to change environment variables and to invoke subprocesses :
您可能还想查看新ProcessBuilder
类,它可以更轻松地更改环境变量和调用子流程:
Process myProcess = new ProcessBuilder(command, arg).start();
...
回答by Felix Leipold
The Java Class Library represents external processes using the java.lang.Process
class. Processes can be spawned using a java.lang.ProcessBuilder
:
Java 类库表示使用java.lang.Process
该类的外部进程。可以使用以下命令生成进程java.lang.ProcessBuilder
:
Process process = new ProcessBuilder("processname").start();
or the older interface exposed by the overloaded exec
methods on the java.lang.Runtime
class:
或由类exec
上的重载方法公开的旧接口java.lang.Runtime
:
Process process = Runtime.getRuntime().exec("processname");
Both of these will code snippets will spawn a new process, which usually executes asynchronously and can be interacted with through the resulting Process
object. If you need to check that the process has finished (or wait for it to finish), don't forget to check that the exit value (exit code) returned by process.exitValue()
or process.waitFor()
is as expected (0 for most programs), since no exception is thrown if the process exits abnormally.
这两个代码片段都会产生一个新进程,该进程通常异步执行并且可以通过生成的Process
对象进行交互。如果您需要检查进程是否已完成(或等待它完成),请不要忘记检查process.exitValue()
或返回的退出值(退出代码)process.waitFor()
是否符合预期(大多数程序为 0),因为没有异常如果进程异常退出,则抛出。
Also note that additional code is often necessary to handle the process's I/O correctly, as described in the documentation for the Process
class(emphasis added):
另请注意,通常需要附加代码来正确处理进程的 I/O,如该类的文档中所述Process
(已添加强调):
By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
默认情况下,创建的子进程没有自己的终端或控制台。它的所有标准 I/O(即 stdin、stdout、stderr)操作将被重定向到父进程,在那里可以通过使用 getOutputStream()、getInputStream() 和 getErrorStream() 方法获得的流访问它们。父进程使用这些流向子进程提供输入和从子进程获取输出。由于一些原生平台只为标准的输入输出流提供有限的缓冲区大小,未能及时写入输入流或读取子进程的输出流可能会导致子进程阻塞,甚至死锁。
One way to make sure that I/O is correctly handled and that the exit value indicates success is to use a library like jproc
that deals with the intricacies of capturing stdout and stderr, and offers a simple synchronous interface to run external processes:
确保正确处理 I/O 并且退出值指示成功的一种方法是使用类似的库jproc
来处理捕获 stdout 和 stderr 的复杂性,并提供一个简单的同步接口来运行外部进程:
ProcResult result = new ProcBuilder("processname").run();
jproc
is available via maven central:
jproc
可通过 Maven 中心获得:
<dependency>
<groupId>org.buildobjects</groupId>
<artifactId>jproc</artifactId>
<version>2.2.0</version>
</dependency>