Platform-independent way to open arbitrary files in a default text editor

I am trying to find out if there is any platform independent way to open a text file with a default text editor, even if the file does not end with .txt. I tried the following code, but it throws an exception for files that do not have the extension .txt. Works great for files .txt.

       Desktop dt = Desktop.getDesktop();
       try
       {
            dt.open(fileName);      
       }
       catch(Exception e){
          // Catch exception here 
       }
+4
source share
2 answers

Unconfirmed, however:

  • create a symlink via nio
    • with the correct extension
    • in the temporary directory
  • Call Desktop.open()by symbolic link

This works for me locally:

public static void main(String... args) throws IOException {
    Path source = FileSystems.getDefault().getPath(args[0]);
    Path symLink = Files.createTempFile(source.getFileName().toString(), ".txt");
    Files.delete(symLink);
    Files.createSymbolicLink(symLink, source);
    Desktop.getDesktop().open(symLink.toFile());
}

: smoke test.

+2

, - , .

? , Java . .txt, AWT.

  • File.renameTo() .txt
  • ,

, ( ) . , . .

, , .

-2

All Articles