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

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

问题描述

好的.简单的问题.不过,也许不是那么简单的答案:

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

: 我想如果没有办法做到这一点,我可以使用 JOptionPane 并显示文本文件的内容...

解决方案

你可以这样做:

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

此链接指向有关 java.awt.Desktop 的教程文章::><块引用>

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

它是跨平台的,但可能不是所有地方都支持.您可以调用一个方法来检查桌面 API 是否可用,称为 isDesktopSupported(更多解释请参见链接).前几天我正在使用这个 API 在 Swing 客户端中打开 PDF.

很遗憾,有一个已知错误会影响某些 Windows 平台(XP 和 2003)使 JVM 崩溃.一次编写,到处调试,像往常一样.无论如何,对于 Windows,有一个 不错的解决方法,它仍然使用用户的首选应用程序:

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

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

解决方案

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

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

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