How to open user system preferred editor for given file?

后端 未结 4 988
花落未央
花落未央 2020-11-29 08:55

I\'m trying to figure out how to open the system preferred editor for a given file.

Say, we have a file manager, written in Java. User goes to folder and sees the li

相关标签:
4条回答
  • 2020-11-29 09:07

    Check out the java.awt.Desktop object. In your case, you want to invoke edit()

    If you want to ensure that a given platform supports this call, then you can do something like the following (I have not tested this code):

    public boolean editFile(final File file) {
      if (!Desktop.isDesktopSupported()) {
        return false;
      }
    
      Desktop desktop = Desktop.getDesktop();
      if (!desktop.isSupported(Desktop.Action.EDIT)) {
        return false;
      }
    
      try {
        desktop.edit(file);
      } catch (IOException e) {
        // Log an error
        return false;
      }
    
      return true;
    }
    
    0 讨论(0)
  • 2020-11-29 09:16

    Seems that if you can't use java.awt.Desktop you have to distinguish between the OSes: Windows:

    RUNDLL32.EXE SHELL32.DLL,OpenAs_RunDLL <file.ext>
    

    Linux:

    edit <file.ext>
    

    Mac:

    open <file.ext>
    

    HTH. Obviously, that is not very portable...

    0 讨论(0)
  • 2020-11-29 09:22

    This will work in windows

    Runtime.getRuntime().exec( "CMD /C START filename.ext " );
    
    0 讨论(0)
  • 2020-11-29 09:28

    This isn't cross-platform, but on Mac OS X you can do

    Runtime.getRuntime().exec("open filename");
    

    The open(1) executable uses LaunchServices to pick the right program to execute, and then uses that to open the file named filename.

    0 讨论(0)
提交回复
热议问题