Create a file association with a Java program

From CodeCodex



In this example, a file with the extension .xox will be defined and associated with a java program (display the first 10 lines of selected .xox file).

First the java program to be associated with the .xox file type.


public class Head {
  static final int MAX_LINES = 10;
  public static void main(String args[]) throws Exception{
    String line = null;
    int i = 0 ;
    FileInputStream fin =  new FileInputStream(args[0]);
    BufferedReader myInput = new BufferedReader
      (new InputStreamReader(fin));
    while ( (line = myInput.readLine()) != null) {
      if (i == MAX_LINES) break;
    BufferedReader input =
      new BufferedReader(new InputStreamReader(;
    System.out.print("*** Press any key...");

With Windows, two commands are used to define a file association, assoc and ftype. You need to execute these commands from an account with Administrator privilege.

To know more about these commands, type assoc /? or ftype /? .

First we define the .xox file type.

The assoc command sets up an association between a file name extension and a file type.

>assoc .xox=Xoxfile

Then we specify which program is used to handle the Xoxfile type of file.

The ftype command sets up an association between a file type name, and a string to be used to execute it.

In this example, we specify the Java JVM to be used, the classpath to load the Head.class plus the parameter (the selected .xox file).

>ftype Xoxfile=C:\Program Files\Java\jre1.5.0\bin\java -cp c:\dev\work Head %1
Xoxfile=C:\Program Files\Java\jre1.5.0\bin\java -cp c:\dev\work Head %1

Now, if you double-click on a file with .xox extension, a Dos shell is opened, the Head class is launched with the clicked filename as a parameter and the first 10 line are displayed.

To make the file association works from a command line, you define the environment variable PATHEXT to include the .xox extension.

>set pathext=.xox;%pathext%

then you will be able, from a Dos shell, to type only the name of .xox file and the associated program will be launched with that file as a parameter. See also this HowTo.