Created
January 12, 2009 15:25
-
-
Save matthewmccullough/46017 to your computer and use it in GitHub Desktop.
Executes a shell command (a.k.a. Shell Execute) from java, such as to open a PDF file or other registered file type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code won't work, you waitFor() before creating the reading stream.
And your if(printShellOutput) would be better if it skipped all the BufferedReader creation & loop