如何使用java代码打开Windows文件资源管理器并突出显示指定文件?

发布于 2024-12-04 00:25:04 字数 203 浏览 2 评论 0原文

我现在使用 java Desktop API 来操作文件资源管理器。 我知道如何打开文件资源管理器,但不知道如何打开它并突出显示指定的文件。

当我们使用Chrome时,下载文件后,我们可以选择“在文件夹中显示”来打开文件资源管理器并突出显示下载的文件。

如何使用java Desktop API来做到这一点? 或者java中有没有其他API可以实现这个动作?

I am now using java Desktop API to manipulate file explorer.
I know how to open the file explorer but I don't know how to open it and highlight the specified file.

As we using the Chrome, after downloading files, we can choose "show in folder" to open the file explorer and highlight the downloaded file.

How to use java Desktop API to do so?
Or is there any other API in java can realize this action?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

怼怹恏 2024-12-11 00:25:04

使用: Runtime.getRuntime().exec("explorer.exe /select,\"" + path + "\"");

如果 PATH 中有空格,这也有效。

Use: Runtime.getRuntime().exec("explorer.exe /select,\"" + path + "\"");

This also works if there is a space in the PATH.

凉宸 2024-12-11 00:25:04

编辑:

从 java 9 开始,桌面 API 中有一种选择文件的方法

desktop.browseFileDirectory(<file>)

编辑:

您无法使用 java 桌面 API 突出显示特定文件。

原始问题的答案:

桌面 API 将允许您使用此代码片段来执行此操作,

File file = new File ("c:\<directory>");
Desktop desktop = Desktop.getDesktop();
desktop.open(file);

上面使用的代码的文档位于这些链接,
http://docs.oracle.com/javase/10 /docs/api/java/awt/Desktop.html
http://docs.oracle.com/javase/10 /docs/api/java/io/File.html

在 Windows 计算机上,这将打开默认文件资源管理器,在其他系统上,它将分别打开其默认资源管理器。

或者,您可以使用新的 java Path API 构建所需的路径,然后调用返回相应 File 对象的方法。

为了简洁起见,我排除了检查代码以确保桌面和文件对象存在。

EDIT:

As of java 9 there is now a method in the Desktop API to select the file

desktop.browseFileDirectory(<file>)

EDIT:

You cannot highlight a specific file with the java Desktop API.

ANSWER TO ORIGINAL QUESTION:

The Desktop API will allow you to do this by using this snippet,

File file = new File ("c:\<directory>");
Desktop desktop = Desktop.getDesktop();
desktop.open(file);

The documentation for the code used above is at these links,
http://docs.oracle.com/javase/10/docs/api/java/awt/Desktop.html and
http://docs.oracle.com/javase/10/docs/api/java/io/File.html

On a Windows computer this will open the default file explorer and on other systems it will open their default explorers respectively.

Alternatively you could use the new java Path API to build the required path and then invoke the method that returns the corresponding File object.

For brevity I excluded the checking code to make sure the Desktop and File objects exist.

向地狱狂奔 2024-12-11 00:25:04

桌面 API 不支持此功能。您将必须使用 ProcessBuilder(或者Runtime.exec()) 显式执行 explorer.exe 您想要的选项。不过,这只适用于 Windows,如果你想在其他操作系统上运行它,你无论如何都必须使用桌面 API。

Process p = new ProcessBuilder("explorer.exe", "/select,C:\\directory\\selectedFile").start();

The Desktop API does not support this. You are going to have to use ProcessBuilder (or alternatively Runtime.exec()) to execute explorer.exe explicitly with the options you want. This will only work on windows though, if you want to run this on another OS you will have to use the Desktop API anyway.

Process p = new ProcessBuilder("explorer.exe", "/select,C:\\directory\\selectedFile").start();
倦话 2024-12-11 00:25:04

我们可以从命令行打开特定路径:

start C:/ProgramData

在java中有两种方法可以使用特定路径打开Windows资源管理器:

  1. 使用Process类(如已经回答的)但使用启动命令

    <前><代码>尝试{
    进程生成器 = Runtime.getRuntime().exec("cmd /c start C:/ProgramData");
    } catch (IOException e) {
    e.printStackTrace();
    }

  2. 使用 Desktop 类

    <前><代码>尝试{
    Desktop.getDesktop().open(new File("C:/ProgramData"));
    } catch (IOException e) {
    e.printStackTrace();
    }

We can open a specific path from command line with :

start C:/ProgramData

There are two ways in java you can use to open windows explorer with specific path:

  1. Use Process class(as already answered) but with start command

    try {
        Process builder = Runtime.getRuntime().exec("cmd /c start C:/ProgramData");
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  2. Use Desktop class

    try {
        Desktop.getDesktop().open(new File("C:/ProgramData"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    
蓝戈者 2024-12-11 00:25:04

始终使用“\”而不是“/”,否则只会打开资源管理器,请先阅读此内容 - 可用于打开 GUI Windows 资源管理器 (Explorer.exe) 的命令行开关

使用 Windows CLI:

C:\Users\Md Arif Mustafa>explorer.exe /select, "C:\Users\Md Arif Mustafa\Music\Aafreen-Himesh.mp3"

与 Java 源代码相同:
这里变量 filePaths 是一个 ArrayList并且包含一个文件夹所有文件路径。

try {
    Process proc = Runtime.getRuntime().exec("explorer.exe /select, " + filePaths.get(i).replaceAll("/", "\\\\"));
    proc.waitFor();
} catch (IOException | InterruptedException ex ) {
    ex.printStackTrace();
}

它对我有用,希望对您有帮助!

Always use the "\" instead of "/", otherwise only the Explorer will open, fore more read this - Command-line switches that you can use to open the GUI Windows Explorer (Explorer.exe)

Using Windows CLI :

C:\Users\Md Arif Mustafa>explorer.exe /select, "C:\Users\Md Arif Mustafa\Music\Aafreen-Himesh.mp3"

Same in Java source code :
Here variable filePaths is an ArrayList<String> and contains a folder all files path.

try {
    Process proc = Runtime.getRuntime().exec("explorer.exe /select, " + filePaths.get(i).replaceAll("/", "\\\\"));
    proc.waitFor();
} catch (IOException | InterruptedException ex ) {
    ex.printStackTrace();
}

It worked for me and hope it helps you!

小傻瓜 2024-12-11 00:25:04

即使文件/文件夹名称在单词之间有多个空格,这也有效。

    //In this example there are 3 spaces between "GAME" and "OF" and 2 spaces between "OF" and "Thrones"
    String onlyPath = "D:\\GAME   OF  Thrones";
    String selectPath = "/select," + onlyPath;        

    //START: Strip one SPACE among consecutive spaces
    LinkedList<String> list = new LinkedList<>();
    StringBuilder sb = new StringBuilder();
    boolean flag = true;

    for (int i = 0; i < selectPath.length(); i++) {
        if (i == 0) {
            sb.append(selectPath.charAt(i));
            continue;
        }

        if (selectPath.charAt(i) == ' ' && flag) {
            list.add(sb.toString());
            sb.setLength(0);
            flag = false;
            continue;
        }

        if (!flag && selectPath.charAt(i) != ' ') {
            flag = true;
        }

        sb.append(selectPath.charAt(i));
    }

    list.add(sb.toString());

    list.addFirst("explorer.exe");
    //END: Strip one SPACE among consecutive spaces

    //Output List
    for (String s : list) {
        System.out.println("string:"+s);
    }
    /*output of above loop

    string:explorer.exe
    string:/select,D:\GAME
    string:  OF
    string: Thrones

    */

    //Open in Explorer and Highlight
    Process p = new ProcessBuilder(list).start();

This works even if file/folder name has multiple spaces between words.

    //In this example there are 3 spaces between "GAME" and "OF" and 2 spaces between "OF" and "Thrones"
    String onlyPath = "D:\\GAME   OF  Thrones";
    String selectPath = "/select," + onlyPath;        

    //START: Strip one SPACE among consecutive spaces
    LinkedList<String> list = new LinkedList<>();
    StringBuilder sb = new StringBuilder();
    boolean flag = true;

    for (int i = 0; i < selectPath.length(); i++) {
        if (i == 0) {
            sb.append(selectPath.charAt(i));
            continue;
        }

        if (selectPath.charAt(i) == ' ' && flag) {
            list.add(sb.toString());
            sb.setLength(0);
            flag = false;
            continue;
        }

        if (!flag && selectPath.charAt(i) != ' ') {
            flag = true;
        }

        sb.append(selectPath.charAt(i));
    }

    list.add(sb.toString());

    list.addFirst("explorer.exe");
    //END: Strip one SPACE among consecutive spaces

    //Output List
    for (String s : list) {
        System.out.println("string:"+s);
    }
    /*output of above loop

    string:explorer.exe
    string:/select,D:\GAME
    string:  OF
    string: Thrones

    */

    //Open in Explorer and Highlight
    Process p = new ProcessBuilder(list).start();
私野 2024-12-11 00:25:04

这是上面的较短版本。

    String onlyPath = "D:\\GAME   OF  Thrones";
    String completeCmd = "explorer.exe /select," + onlyPath;
    new ProcessBuilder(("explorer.exe " + completeCmd).split(" ")).start();

Here is shorter version of above.

    String onlyPath = "D:\\GAME   OF  Thrones";
    String completeCmd = "explorer.exe /select," + onlyPath;
    new ProcessBuilder(("explorer.exe " + completeCmd).split(" ")).start();
风轻花落早 2024-12-11 00:25:04

正确 ProcessBuilder 代码实际上如下:

public static void selectFileInFileExplorer(final Path filePath) throws IOException {
    final String windowsDirectory = System.getenv("WINDIR");
    final String explorerFilePath = windowsDirectory + "\\explorer.exe";
    final ProcessBuilder builder = new ProcessBuilder(explorerFilePath, "/select,", filePath.toString());
    builder.start();
}

注意,需要在 /select, 之后启动一个新命令,否则会打开<代码>文档文件夹。

The correct ProcessBuilder code is actually the following:

public static void selectFileInFileExplorer(final Path filePath) throws IOException {
    final String windowsDirectory = System.getenv("WINDIR");
    final String explorerFilePath = windowsDirectory + "\\explorer.exe";
    final ProcessBuilder builder = new ProcessBuilder(explorerFilePath, "/select,", filePath.toString());
    builder.start();
}

Note that you need to start a new command after /select,, otherwise it will open the Documents folder.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文