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.
Asked
Active
Viewed 2,946 times
4
-
[This question](http://stackoverflow.com/questions/3487149/how-to-open-the-notepad-file-in-java) has the answers you need. – Kevin K Oct 20 '11 at 18:25
3 Answers
5

svaor
- 2,205
- 2
- 19
- 41
-
Note that the Desktop.open(File) method has some bugs. See http://bugs.sun.com/view_bug.do?bug_id=6631015 and http://stackoverflow.com/questions/1527162/java-awt-desktop-open-doesnt-work-with-pdf-files, for example. – fbarber Feb 19 '13 at 04:20
2
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;
}
}

Stephan
- 4,395
- 3
- 26
- 49
0
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\""

diyism
- 12,477
- 5
- 46
- 46