查找关联程序以使用 Java 打开文件
我希望使用计算机上安装的关联程序(在本例中使用 MS Word 或 Open Office Writer)从 Java 应用程序打开文件(比如说,word 文档)。
问题是我想等到这个子进程完成,这可以使用 Process 类中的 waitFor() 方法来完成。
String executable = findAssociatedApplicationPath(); //for example, returns "C:\\Program Files\\Microsoft Office\\Office12\\msword.exe"
Process p = Runtime.getRuntime().exec(executable + " " + filepath);
p.waitFor();
有人可以告诉我如何编写 findAssociatedApplicationPath() 方法以便它返回正确的可执行文件吗?或者还有其他方法可以做到这一点吗?
I wish to open a file (lets say, a word document) from a Java application using the associated program installed on the computer (in this example, using MS Word or Open Office Writer).
The catch is that I want to wait until this subprocess finishes, which can be done using the waitFor() method in the Process class.
String executable = findAssociatedApplicationPath(); //for example, returns "C:\\Program Files\\Microsoft Office\\Office12\\msword.exe"
Process p = Runtime.getRuntime().exec(executable + " " + filepath);
p.waitFor();
Can someone tell me how to write the findAssociatedApplicationPath() method so it returns the correct executable? Or is there another way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用关联程序打开文件的正确的独立于平台的方法是
Desktop.open()
。不幸的是,它没有提供任何与结果过程交互的方式。如果您愿意失去平台独立性,可以使用
cmd.exe
中的start
命令:The proper platform-independant way to open a file using the associated program is
Desktop.open()
. Unfortunately, it does not offer any way to interact with the resulting process.If you're willing to lose platform independance, you can use the
start
command incmd.exe
:没有纯 Java 的方法可以做到这一点,因为它必然是特定于操作系统的。在 Windows 平台上,
start
命令可能就是您想要的正在寻找(例如,start myfile.txt
)。There's no pure Java way to do this, because it's necessarily OS-specific. On a Windows platform, the
start
command is probably what you're looking for (for example,start myfile.txt
).没有“通用”方法可以在所有平台上执行此操作。在 Windows 上,您可以执行“start”,这将找到正确的关联可执行文件。在mac上,可以执行“open”。据我所知,在 Linux 上,恐怕您必须手动映射首选应用程序。
There is no "universal" way to do this across all platforms. On Windows, you can execute "start", which will find the correct associated executable. On the mac, you can execute "open". On Linux, I'm afraid you'll have to map the preferred applications manually as far as I know.
您可以尝试修改 Windows 注册表和其他特定于平台的设置,但我认为最好的解决方案是简单地让应用程序拥有自己的首选项设置。
您可能想使用 中的类
package java.util.prefs
为此。You can try to mess around with the Windows registry and other platform-specific settings, but I think the best solution is to simply have the application have its own preferences setting.
You may want to use the classes in
package java.util.prefs
for this.我已经想通了。
使用 cmd.exe + start.exe 组合,waitFor() 方法将不会等待子进程结束。
如果在没有启动选项的情况下执行此操作,它就像一个魅力(尽管仅限 Windows):
I have figured it out.
Using the cmd.exe + start.exe combo, the method waitFor() will not wait for the subprocess to end.
If doing it without the start option it works like a charm (windows only though):