查找相关的程序使用Java来打开文件 [英] Find the associated program to open a file using Java

查看:115
本文介绍了查找相关的程序使用Java来打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用安装在计算机上的相关的程序(在这个例子中,使用MS Word或开放式办公作家)从Java应用程序打开文件(可以说,一个word文档)。

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

美中不足的是,我要等到这个子完成后,可以使用Process类的WAITFOR()方法来实现。

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

谁能告诉我怎么写findAssociatedApplicationPath()方法,它返回正确的可执行文件?还是有另一种方式来做到这一点?

Can someone tell me how to write the findAssociatedApplicationPath() method so it returns the correct executable? Or is there another way to do this?

推荐答案

适当的平台无关的方式来打开一个文件使用相关程序的 Desktop.open() 。不幸的是,它不提供任何方式用所得进程交互。

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.

如果你愿意失去平台的独立性,您可以使用启动的cmd.exe 命令:

If you're willing to lose platform independance, you can use the start command in cmd.exe:

String fileName = "c:\\tmp\\test.doc";
String[] commands = {"cmd", "/c", "start", "\"Title\"",fileName};
Process p = Runtime.getRuntime().exec(commands);
p.waitFor()

这篇关于查找相关的程序使用Java来打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆