Open a text file in the default text editor… via Java?

懵懂的女人 提交于 2019-11-26 13:07:31

问题


OK. Simple question. Maybe not so simple answer, though:

I have a file I downloaded in Java, and I know that it\'s a text file. Is there any way that I can use Java to open that text file in whatever the default text editor is? It has to work for all OS\'s, otherwise I would just make it open with Notepad.

:\\ I guess that if there\'s no way to do this I could use JOptionPane and show the contents of the text file...


回答1:


You can do that with:

java.awt.Desktop.getDesktop().edit(file);

This links to the tutorial article on java.awt.Desktop:

Java™ Standard Edition version 6 narrows the gap between performance and integration of native applications and Java applications. Along with the new system tray functionality, splash screen support, and enhanced printing for JTables , Java SE version 6 provides the Desktop API (java.awt.Desktop) API, which allows Java applications to interact with default applications associated with specific file types on the host platform.

It is cross-platform, but may not be supported everywhere. There is a method you can call to check whether the Desktop API is available, called isDesktopSupported (see the link for more explanation). I was using this API the other day to open PDFs in a Swing client.

Unfortunately there is a known bug affecting some Windows platforms (XP and 2003) that will crash the JVM. Write once, debug everywhere, as usual. Anyway, for Windows there is a nice workaround which still uses the user's preferred application:

if (System.getProperty("os.name").toLowerCase().contains("windows")) {
  String cmd = "rundll32 url.dll,FileProtocolHandler " + file.getCanonicalPath();
  Runtime.getRuntime().exec(cmd);
} 
else {
  Desktop.getDesktop().edit(file);
}



回答2:


Desktop.getDesktop().edit(File f);



回答3:


Certainly you could configure in the text editor and use Runtime.exec to start it. But I can't think of any way to determine the default editor, especially in a system-independent fashion.

Maybe your best option is to identify which of the several most popular platforms you're on and then find a way to start the default editor on that platform. Eg, on Window you'll get the default editor if you do "start filename.txt", and I'm pretty sure there's a Linux equivalent.



来源:https://stackoverflow.com/questions/6273221/open-a-text-file-in-the-default-text-editor-via-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!