How to open and view a file(similar to that of double clicking a file) using Java

3k views Asked by At

I would like to know to know the code in Java that that will help perform the same operation as that of a double click in any OS on a file making it open and thereby enable us to view its contents when the user supplies the location of the file in his/her PC. Any suggestion would be of great help as i need it to finish my application.

3

There are 3 answers

1
svaor On BEST ANSWER
0
Stephan On

I used the following code. On windows, you will get a windows file open dialog if no program is associated with the file type. If it does not run on windows, it falls back to Desktop.open(), which works if the file type is known to the system.

public static boolean openFile(File file){
  try {
    if (System.getProperty("os.name").contains("Windows")) {
      Runtime.getRuntime().exec(
          "rundll32 SHELL32.DLL,ShellExec_RunDLL " + file.getAbsolutePath());
    } else if (Desktop.isDesktopSupported()) {
      Desktop.getDesktop().open(file);
    } else {
      return false;
    }
    return true;
  } catch (final Exception e1) {
    System.err.println("Error opening file " + file, e1);
    return false;
  }
}
0
diyism On

in windows xp:

rundll32 shell32.dll,ShellExec_RunDLL "file:///d:\download\theapp.lnk"

you could add registry so that you could run lnk file in RUN dialog box and folder cruiser:

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\lnkfile\shell]

[HKEY_CLASSES_ROOT\lnkfile\shell\edit]

[HKEY_CLASSES_ROOT\lnkfile\shell\edit\command]
@="rundll32 shell32.dll,ShellExec_RunDLL \"file:///%1\""