How do you open a file from a java application when you do not know which application the file is associated with. Also, because I'm using Java, I'd prefer a platform independent solution.
            Asked
            
        
        
            Active
            
        
            Viewed 3.3k times
        
    3 Answers
42
            With JDK1.6, the java.awt.Desktop class can be useful.
public static void open(File document) throws IOException {
    Desktop dt = Desktop.getDesktop();
    dt.open(document);
}
        Bhesh Gurung
        
- 50,430
 - 22
 - 93
 - 142
 
        RealHowTo
        
- 34,977
 - 11
 - 70
 - 85
 
- 
                    Is this piece of code also works on linux? – Siddhartha Sadhukhan Jul 23 '17 at 14:58
 - 
                    Yes ... but it is a good idea to call `Desktop.isDesktopSupported()` or `Desktop.isSupported(action)` first, see the Javadoc. – RealHowTo Jul 27 '17 at 19:55
 
5
            
            
        File file
Desktop.getDesktop().open( file );
Since Java 1.6
Previous to that you could check this question
Summary
It would look something like this:
Runtime.getRuntime().exec( getCommand( file ) );
public String getCommand( String file ){ 
    // Depending on the platform could be
    //String.format("gnome-open %s", fileName)
    //String.format("open %s", fileName)
    //String.format("cmd /c start %s", fileName)
    // etc. 
}
- 
                    I'd like to add "xdg-open" (http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html) for a more integrated Linux-command that isn't available everywhere. – Joachim Sauer Dec 24 '08 at 09:25
 
2
            
            
        You could hack something together with a bat file on Windows and equivalent on Unix, but that wouldn't be that fun.
I think your best bet would be the JDesktop Integration Components (JDIC). In particular, the Desktop class has exactly the method you're looking for.
EDIT: Apparently, I'm behind the times because this has been integrated into Java 1.6. In any case, if you're working in an earlier Java, it may still be useful.
        Dave Ray
        
- 39,616
 - 7
 - 83
 - 82