Reputation: 542
I have a Java program that asks the user to enter in the path to a file that needs to be executed.
the path can be something like this for example: C:/ProgramFiles/Citrix/ICA Client/pnagent.exe
I create a File
Object with this path, and check to make sure it exists, and check to make sure it's a File, and check to make sure it's executable. as far as File
is concerned, it's a completely valid Object that exists.
note: the File
object is called "script"
BUT When I run the script, I receive errors on the spaces.
Runtime rt = java.lang.Runtime.getRuntime();
Process pp = rt.exec(script.getAbsolutePath());
I am 100% the first line works correctly. The error I receive is the image below: (I have it displayed in a JOptionPane.)
What is the best way to remove my errors? Thanks in advanced!
Attempted Solution #1:
Process pp = rt.exec("\""+script.getAbsolutePath()+"\"");
When I use C:\Tools\IT Support\bookmark.htm
I get
Upvotes: 2
Views: 2267
Reputation: 35372
Try
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",script.getAbsolutePath()};
Runtime.getRuntime().exec(commands);
It is a Windows only solution.
java.awt.Desktop is maybe a better solution in your situation since you need the "file-association" mechanism.
public static void open(File document) throws IOException {
Desktop dt = Desktop.getDesktop();
dt.open(document);
}
Upvotes: 1
Reputation: 1487
EDIT:
By far the most reliable way is to use Runtime.exec(String[] cmdarray).
If you use Runtime.exec(String command), Java only splits the command on whitespace.
the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.
See also g++: File not found
Or use ProcessBuilder something like this:
ProcessBuilder pb = new ProcessBuilder("ln", "-s", "dir1/dir2", "my dir/dir2");
Process p = pb.start();
Upvotes: 4