0

I am encountering a problem with file associations in Java (using the terminal command JPackage for building an executable file). The problem is basically the following: when I try to open a file with my application, the file path is not passed to my main method as an argument. Let me share a simplified example of the code below. I am working on IntelliJ Idea on MacOs 12 (Monterey).

This is the (only) class, containing the main method, from which I build an executable .jar file.

import javax.swing.*;
import java.awt.*;

public class Main {

public static void main(String[] args) {

    if (args.length == 0) {

        JFrame frame = new JFrame("Test");
        JLabel label = new JLabel("No arguments");
        frame.setLayout(new BorderLayout());
        frame.add(label, BorderLayout.CENTER);
        frame.setPreferredSize(new Dimension(1000,500));
        frame.pack();
        frame.setVisible(true);

    } else if (args.length == 1) {

        JFrame frame = new JFrame("Test");
        JLabel label = new JLabel(args[0]);
        frame.setLayout(new BorderLayout());
        frame.add(label, BorderLayout.CENTER);
        frame.setPreferredSize(new Dimension(1000,500));
        frame.pack();
        frame.setVisible(true);

    }
}
}

This is the ".properties" file I have written, to set the file association with the ".txt" file type.

mime-type=text/plain
extension=txt
description=Text Source

Finally, here is the terminal command I used to build the executable file for MacOs.

jpackage --type "app-image" --name JavaGuiApp --input /Users/username/Desktop/JavaGuiApp --main-jar JavaGuiApp.jar --file-associations /Users/username/Desktop/JavaGuiApp/FAtxt.properties

I have relied on information found here on JPackage: https://docs.oracle.com/en/java/javase/14/jpackage/packaging-overview.html.

Thank you all in advance for your help!

andy_07
  • 21
  • 5
  • You are just checking for zero and one arguments on startup. AFAIK the first argument always contains the application name itself and should always exist. Have you checked conditions when there are more arguments? – Queeg Jan 01 '22 at 12:39
  • @HiranChaudhuri Hi! I have added a System.out.println(args[0]) in both conditional blocks, and when starting the application "normally" - without opening a file, which should correspond to the case "args.length == 0" - it raises an ArrayIndexOutOfBoundsException, so I guess probably when it is started without passing a file path it actually has no arguments (hence the exception). I have also tried adding an "args.length == 2" conditional block, but it still does not work. – andy_07 Jan 01 '22 at 13:03

0 Answers0