使用 Java 打开外部非 java 文件
我正在尝试访问文件“J:\Java\NetBeansProjects\List offorken things\list.eml”并使用操作系统定义的默认应用程序打开它。这可以通过调用在命令提示符中完成,
cd "J:\Java\NetBeansProjects\List of forgoten things"
"list.eml"
所以我决定使用
Runtime.getRuntime().exec("cd \"" + System.getProperty("user.dir") + "\"\n\r" + "\"" + selectedFile.getName() + "\"");
,但它不断给我一个 IOException:
java.io.IOException: Cannot run program "cd": CreateProcess error=2, The system cannot find the file specified
有人有任何经验或建议想要分享吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
cd
不是真正的可执行文件 - 它是 shell 内置命令。此外,我认为您想要做的是在 Java 6 中使用
Desktop
,特别是open
方法,尝试使用平台上默认注册的应用程序打开文件(如果存在)。http://download.oracle.com/javase/ 6/docs/api/java/awt/Desktop.html
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 theopen
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
发生这种情况是因为 exec 尝试将 cd 命令作为真实文件执行,而它只是 shell 命令 (cmd.exe)。
您可以尝试调用
cmd /C "cdwhateverdir "
将命令传递给 shell exe 或使用.bat
文件。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.在执行文件之前,您不需要
CD
到该目录。只需提供完整路径即可。You don't need to
CD
to the directory before executing the file. Just provide the full path.