开发者

System Commands - Java

开发者 https://www.devze.com 2023-04-02 21:20 出处:网络
I\'m trying to make a little java program that executes a system command but I can\'t se开发者_运维技巧em to figure it out

I'm trying to make a little java program that executes a system command but I can't se开发者_运维技巧em to figure it out

The question is how does one execute a system command using java?

UPDATE: I read the documentation & tried some examples & I still can't figure it out. Why can't it be simple like in C.


You might want to have a look into the documentation for java.lang.ProcessBuilder. An example is given there.


Process Builder example


Ultimately, you use the family of exec() methods in the java.lang.Runtime class. There's a class named java.lang.ProcessBuilder which helps in setting up a process to run, although you're not obligated to use it. Be sure to read this classic article on handling the input and output streams, running Windows CMD.EXE builtins, and other potential pitfalls.

Running a command can be as simple as saying

Runtime.exec("notepad");

but as that article points out, there are plenty of subtleties to worry about.


Apache Commons-Exec is similar to ProcessBuilder, but helps avoid a lot of common problems with the streams, process timeout, platform differences, etcetera. I recommend using that instead of ProcessBuilder.

0

精彩评论

暂无评论...
验证码 换一张
取 消