1

我正在尝试访问文件“J:\Java\NetBeansProjects\List of forgoten 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

有没有人想分享任何经验或建议?

4

3 回答 3

4

cd不是真正的可执行文件 - 它是一个 shell 内置命令。

此外,我认为您想要做的是Desktop在 Java 6 中使用,特别是open方法,它尝试使用平台上的默认注册应用程序(如果存在)打开文件。

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

于 2010-10-18T02:16:29.677 回答
2

发生这种情况是因为 exec 尝试将cd命令作为真实文件执行,而它只是 shell (cmd.exe) 的命令。

您可以尝试通过调用cmd /C "cd whateverdir "将命令传递给 shell exe 或使用.bat文件。

于 2010-10-18T02:18:55.127 回答
0

在执行文件之前,您不需要CD进入目录。只需提供完整路径。

String fileName=System.getProperty("user.dir") + selectedFile.getName();
Runtime.getRuntime().exec(fileName);
于 2010-10-18T06:18:52.673 回答