通过Java在默认的文本编辑器中打开一个文本文件? [英] Open a text file in the default text editor... via Java?

查看:493
本文介绍了通过Java在默认的文本编辑器中打开一个文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

行。简单的问题。可能不是这么简单的答案,但是:

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

我有一个我在Java中下载的文件,我知道它是一个文本文件。有什么办法可以使用Java打开任何默认文本编辑器的文本文件吗?它必须适用于所有的操作系​​统,否则我只是用记事本打开。

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.

:\我猜,如果没有办法这样做,我可以使用JOptionPane并显示文本文件的内容...

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

推荐答案

您可以通过以下方式执行:

You can do that with:

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

此链接指向关于java.awt.Desktop的教程文章


Java™标准版版本6
缩小了性能
与本地应用程序
和Java应用程序的集成之间的差距。随着
新的系统托盘功能,飞溅
屏幕支持和增强打印
为JTables,Java SE版本6
提供了Desktop API
(java.awt .Desktop)API,它允许
Java应用程序与
默认应用程序交互,与
相关联的特定文件类型在主机
平台上。

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.

它是跨平台的,但可能无处不在。有一种方法可以调用来检查Desktop API是否可用,称为isDesktopSupported(有关更多说明,请参阅链接)。我正在使用这个API在Swing客户端打开PDF。

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.

不幸的是有一个影响某些Windows平台(XP和2003)的已知错误将导致JVM崩溃。写一下,像往常一样调试无处不在。无论如何,对于Windows,还有一个仍然使用用户首选应用程序的不错的解决方法

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

这篇关于通过Java在默认的文本编辑器中打开一个文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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