Revisions

gist: 46017 Download_button fork
public
Description:
Executes a shell command (a.k.a. Shell Execute) from java, such as to open a PDF file or other registered file type
Public Clone URL: git://gist.github.com/46017.git
Embed All Files: show embed
JavaShellExecute.java #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/**
* A Java method to execute and wait for a shell command to complete
*/
public class JavaShellExecute
{
    public static void main(String[] args) throws Exception {
        runShellCommand("open somefile.txt", true);
    }
 
    /**
* The OPEN command on MacOSX causes the registered file handler to open a file.
* The START command on Windows causes the registered file handler to open a file.
*
* Example param can include a path and file such as:
* "open yourpath/somefile.txt"
*/
public static void runShellCommand(String shellCommand, boolean printShellOutput) throws IOException, InterruptedException {
Runtime runtime = Runtime.getRuntime() ;
Process shellProcess = runtime.exec(shellCommand) ;
 
//Only wait for if you need the external app to complete
shellProcess.waitFor() ;
        
//You can read the contents of the application's information it is writing to the console
BufferedReader shellCommandReader = new BufferedReader( new InputStreamReader(shellProcess.getInputStream() ) ) ;
 
String currentLine = null;
while ( (currentLine = shellCommandReader.readLine() ) != null )
{
if (printShellOutput)
                System.out.println(currentLine);
}
}
}