java:单击按钮打开文件夹 [英] java: Open folder on button click
问题描述
在java中,我们如何通过单击按钮为用户打开单独文件夹(例如c:),例如在磁盘上找到此文件"或打开包含文件夹"的方式当我们下载文件并且我们想知道它的保存位置时会这样做.目标是节省用户打开浏览器并在磁盘上定位文件的时间.谢谢(下图是firefox所做的一个例子)
In java, how can we open a separate folder (e.g. c:) for user on click of a button, e.g like the way " locate this file on disk" or "open containing folder" does when we download a file and we want to know where it was saved. The goal is to save user's time to open a browser and locate the file on disk. Thanks ( image below is an example from what firefox does)
我得到了答案:以下是在 Windows 7 中对我有用的方法:
I got the answer: Here is what worked for me in Windows 7:
File foler = new File("C:\\"); // path to the directory to be opened
Desktop desktop = null;
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
}
try {
desktop.open(foler);
} catch (IOException e) {
}
感谢@AlexS
推荐答案
我假设你有一个文件.使用 java.awt.Desktop,您可以使用以下内容:
I assume you have a file. With java.awt.Desktop you can use something like this:
public static void openContaiingFolder(File file) {
String absoluteFilePath = file.getAbsolutePath();
File folder = new File(absoluteFilePath.substring(0, absoluteFilePath.lastIndexOf(File.separator)));
openFolder(folder);
}
public static void openFolder(File folder) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(folder);
}
}
请注意,如果您使用不是目录的文件调用此方法,至少 Windows 将尝试使用该文件类型的默认程序打开该文件.
Be awrae that if you call this with a File that is no directory at least Windows will try to open the file with the default program for the filetype.
但我不知道在哪些平台上支持.
But I don't know on which platforms this is supported.
这篇关于java:单击按钮打开文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!