0

I'm needing to open a folder containing the specified file, and highlight this said file. I have been looking for this for long but I have been unlucky. Could someone explain how this could be done using java?

Would be much appreciated. I am able to open files, folders, but not open the containing folder and highlighting a file. Cross platform code would be a plus, or just point me to the direction! Thanks!

@UPDATE:

Basically I'm doing an image sorter. I have a ArrayList containing filenames, e.g. myarraylist.get(0) would return funny_cat.jpg

This can be a handy functionality to have in a program that works with files/folders. It's easy enough to actually open the containing folder using:

I want the user to be able to open the currently selected item in a JList and open the containing folder with the target file selected.

I would post the code but it is too long and most unnecesary for this question, I will however post below how I open an explorer window, for the settings section of program, in order to choose a new directory to use:

public void browseFolder(){

     System.out.println("browsing!");

        final JFileChooser fc = new JFileChooser();

        File dir = new File(core.Loader.path);

        fc.setCurrentDirectory(dir);

        // Windows and Mac OSX compatibility code
        if (System.getProperty("os.name").startsWith("Mac OS X")) {

            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        } else {
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        }


        fc.setApproveButtonText("Choose directory");
        int returnVal = fc.showOpenDialog(fc);

            if (returnVal == JFileChooser.APPROVE_OPTION) {


                File f = fc.getSelectedFile();
                // if the user accidently click a file, then select the parent directory.
                if (!f.isDirectory()) {
                    f = f.getParentFile();
                }

                // debug
                System.out.println("Selected directory for import " + f);

            }
}

@UPDATE

I have found the solution, will post as answer below.

4

1 回答 1

2

所以,我只是从执行的操作中调用了这个方法,它就成功了。

基本上,解决方案是制作这个终端命令:

open -R absolute/path/to/file.jpg

这仅适用于 Mac OS X,以下是我使用的方法:

 public void openFileInFolder(String filename){

    try {
       Process ls_proc;

       String mvnClean = "open -R " + core.Loader.path + "/" + file_chosen;
       String OS = System.getProperty("os.name");

       System.out.println("OS is: " + OS);

       if (OS.contains("Windows")) {
           //code ...
       } else {
           ls_proc = Runtime.getRuntime().exec(mvnClean);
       }

     } catch (Exception e){
          System.err.println("exception");
     }
}
于 2013-09-30T21:15:10.100 回答