简体   繁体   中英

Opening an external, non-java file with Java

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?

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM