Executing files with Windows native handler

As I am currently building a cross platform file-manager for our document management tool in Java, I am in need for a way to have files executed by the Windows (and other OSes, but for most clients; Windows) shell as they would be executed when clicking on them in the Windows file explorer.

Doing this in Java is quite easy and a lot of people already figured that out, you simply use the rundll32 command to execute the following:

rundll32 url.dll,FileProtocolHandler URL

where URL can be something on internet or on your local drive. Say you want to ‘run’ a .txt file on your c: drive:

rundll32 url.dll,FileProtocolHandler file:///mytextfile.txt

opens, on my system with notepad.

The problem with this method is, that if there is no handler, nothing will happen…

After playing around a bit with the registry I found the following;

reg query HKCR.ext

gives you information about the extension and what Windows will do with it.

In general, as I have discovered (correct me if I am wrong please!), if is in the result, the file can and will be executed by Windows. You can even use it to extract the file type. Example:

C:>reg query HKCR.dot

! REG.EXE VERSION 3.0

HKEY_CLASSES_ROOT.dot
<NO NAME> REG_SZ OpenOffice.org.dot

HKEY_CLASSES_ROOT.dotPersistentHandler

So the code for running a file with the default associated application under Windows would be:

String file = “/test.html”;
String ext = file.substring(file.lastIndexOf(‘.’));

Process p = Runtime.getRuntime().exec(“reg query HKCR\” + ext);
InputStream in = p.getInputStream();
p.waitFor();
byte[] buffer = new byte[in.available()];
in.read(buffer);
String result = new String(buffer);
in.close();

if (result.indexOf(“<NO NAME>”) > -1) {
p = Runtime.getRuntime().exec(“rundll32 url.dll,FileProtocolHandler file://”+file);
} else {
System.err.println(“No handler available for “+file);
}


There are probably ways to do this faster/easier, but currently we are not in need of this. However, if you know ways to do it, please comment on this post.

Be the first to leave a comment. Don’t be shy.

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>