views:

51

answers:

3

I am trying to access the file "J:\Java\NetBeansProjects\List of forgoten things\list.eml" and open it using the OS-defined default application. This can be acomplished in the command prompt by calling

cd "J:\Java\NetBeansProjects\List of forgoten things"
"list.eml"

so I decided to use

  Runtime.getRuntime().exec("cd \"" + System.getProperty("user.dir") + "\"\n\r" + "\"" + selectedFile.getName() + "\"");

but it keeps giving me an IOException:

 java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified

does anyone have any experience or advice they would like to share?

+4  A: 

cd is not a real executable - it is a shell built-in command.

Additionally, I think what you want to do is use Desktop in Java 6, specifically the open method, which attempts to open a file with the default registered application on the platform (if it exists).

http://download.oracle.com/javase/6/docs/api/java/awt/Desktop.html

birryree
but it ran the "shutdown" command, for me... How do I run shell commands, then?
Supuhstar
`shutdown` is a real command in Windows, located in `%WINDIR%/system32`. Please see my edit for a possible solution to your problem.
birryree
Thank you! "java.awt.Desktop.getDesktop().open(selectedFile);" did the trick!
Supuhstar
+1  A: 

This happens because exec tries to execute the cd command as a real file while it's only a command of shell (cmd.exe).

You could try by invoking cmd /C "cd whateverdir " to pass the command to shell exe or using a .bat file.

Jack
A: 

You don't need to CD to the directory before executing the file. Just provide the full path.

String fileName=System.getProperty("user.dir") + selectedFile.getName();
Runtime.getRuntime().exec(fileName);
MattD