Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a command from Java and NOT wait for the result

I'm building a command line string in my Java application (e.g. "winword.exe FinalReport.doc"). I want to execute the command and let it go: I don't want/need to wait for the result (max would be: did it start right, but that's optional) and the application needs to continue running when my Java application has terminated.

I had a look at Runtime.getRuntime().exec() and Apache Commons_Exec. Both keep in control of the launched app (with commons and a callback clearly preferable), but that's not what I need. What do I miss?

Do I need to call the Windows/Linux/Mac API to launch an independent app?

like image 586
stwissel Avatar asked Aug 10 '11 13:08

stwissel


2 Answers

There is an easy cross-platform way to do this, using the java.awt.Desktop api, like this:

File file = new File("FinalReport.doc");
java.awt.Desktop.getDesktop().edit(file);

This opens up whatever application the user has specified has his preferred editor for that file, in another process entirely separate from your application (and you don't need to worry about possibly getting locked up from not reading from the created process' stdout the way you would using ProcessBuilder). You don't need to use platform-specific code or even know what applications are available on the user's platform.

like image 21
Nathan Hughes Avatar answered Oct 06 '22 00:10

Nathan Hughes


try using Process! this is how I am using it in my app:

Process process = new ProcessBuilder()
                    .command(convert, image.name, "-thumbnail", "800x600>", bigsize.name)
                    .directory(image.parentFile)
                    .redirectErrorStream(true)
                    .start()

I would guess, you can use like:

Process process = new ProcessBuilder()
                    .command("winword.exe", "FinalReport.doc")
                    .directory(new File("C:/"))
                    .redirectErrorStream(true)
                    .start()
like image 92
Arthur Neves Avatar answered Oct 05 '22 22:10

Arthur Neves