简体   繁体   中英

Is there platform-agnostic code in Java to invoke the default app to view document types like PDF, DOCX, JPEG etc.?

I would like to write a Java class (or method) whose responsibility is to invoke the standard/default application on any platform for opening and handling files of specific formats such as PDF, DOCX, XLSX, JPG etc. and also to know if no suitable application for that file format is available.

Is there a nice, cross-platform way of doing this?

To be honest...the answer is no big secret, after all the Desktop Class has been around since Java 1.6.

To open a file with its associative application (ie: .docx with MS WORD or whatever application the system has associated to the file) then you can use the Desktop.getDesktop().open() method. This method should go hand in hand with the Desktop.isDesktopSupported() method so as to ensure the Desktop Class is supported on the current platform. Here is a small method to demonstrate the use of the above Desktop Class methods:

public void runFile (String filePath) throws IOException {
    File myFile = new File(filePath);
    //Test whether the Desktop class is supported on the current platform.
    if (Desktop.isDesktopSupported()) {
        // Open the file in its associated application:
        Desktop.getDesktop().open(myFile);
    }
    else {
        // Desktop Not Supported...
        System.err.println("runFile() method error! The Desktop Class " +
                           "is not supported on this platform!");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM