Java: open a folder when a button is clicked

In java, how can we open a separate folder (for example, c :) for the user at the click of a button, for example, like โ€œfind this file on diskโ€ or โ€œopen folder with folderโ€ when we upload the file and we want to know where it has been saved. The goal is to save user time in order to open a browser and find the file on disk. Thanks (the image below is an example of what firefox does) enter image description here

I got the answer: Here is what worked for me on 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) { } 

Thanks @AlexS

+6
source share
1 answer

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

Be careful if you call this with a file that is not a directory, at least Windows will try to open the file with the default program for the file type.

But I do not know on which platforms this is supported.

+10
source

Source: https://habr.com/ru/post/907606/


All Articles