I am trying to invoke an HTML File stored on my desktop from inside a JAVA code as below.
I found this code snippet here
try
{
Runtime r= Runtime.getRuntime();
String url = "C:\\Users\\Rana\\Desktop\\test.html";
String browser ="C:/Program Files/Mozilla Firefox/firefox.exe ";
Process p = r.exec(browser);
p.waitFor();
}
catch(Exception e)
{
e.printStackTrace();
}
I tried using backslash and forward slashes, both. But it is throwing this error in both case....
java.io.IOException: Cannot run program "C:/Program": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at java.lang.Runtime.exec(Runtime.java:617)
at java.lang.Runtime.exec(Runtime.java:450)
at java.lang.Runtime.exec(Runtime.java:347)
at package1.Test.main(Test.java:22)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:376)
at java.lang.ProcessImpl.start(ProcessImpl.java:136)
The path "browser" is present.
Please suggest where I am doing wrong.
6 Answers 6
The issue is with the space in your path to the browser. The system thinks you are trying to run a program called "C:/Program" with "Files/Mozilla" and "Firefox/firefox.exe" as the arguments. Try adding quotes around the exe name:
String browser ="\"C:/Program Files/Mozilla Firefox/firefox.exe\" ";
To incorporate SnakeDoc's advice, you could use the environment variable to take care of the portion of the path down to "Program Files", but you will still need the quotes to take care of any other spaces in the path:
String browser = "\"" + System.getenv("ProgramFiles(X86)") + "Mozilla Firefox/firefox.exe\"";
6 Comments
String browser = System.getenv("ProgramFiles(X86)") + "Mozilla Firefox/firefox.exe";String browser = "\"" + System.getenv("ProgramFiles(X86)") + "Mozilla Firefox/firefox.exe\"";Try using the system properties:
System.getenv("ProgramFiles");
or
System.getenv("ProgramFiles(X86)");
Comments
Better advice,
use AutoHotKey for such tasks.You should give it a try.I promise you would definitely find it useful.
Comments
if you are using the 32bit version browser should be String browser ="C:/Program Files(x86)/Mozilla Firefox/firefox.exe ";
hope this helps
Comments
Try
String browser ="\"C:/Program Files/Mozilla Firefox/firefox.exe\"";
There is problem with space in Program files that get treated as separator if not inside Quotes. It is briliant idea by Microsoft...
Comments
The best way would be to do this with java.awt.Desktop
File htmlFile = new File("C:" + File.separator + "Users" + File.separator + "theuser" + File.separator + "Desktop" + File.separator + "Test.html");
if(Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(htmlFile);
}
Cannot run program C:/Program-- which isn't what you are trying to run. I think the space in the path is making it not work.