Skip to content

Instantly share code, notes, and snippets.

@matthewmccullough
Created January 12, 2009 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewmccullough/46017 to your computer and use it in GitHub Desktop.
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
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);
}
}
}
@DeepSnowNeeL
Copy link

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

@Ashish-Chamoli
Copy link

@matthewmccullough Thanks!!
Code ran for me :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment