Search code examples
javaeclipsedictionaryjarbuildpath

How to add a .dic and .aff file to a java jar?


I was wondering if there is a way to add .dic and .aff files to a java project jar file (using eclipse for example)?

I have in my code a dictionary:

    URL dicDic = CipherTextAttack.class.getResource("en_US");
    static Hunspell.Dictionary dict = Hunspell.getInstance().getDictionary(dicDic.toString());

I need the jar file to run everywhere without needing the en_US dictionary file.. Is that possible?


Solution

  • Yes, a jar file is basically a zip file with a .jar extension, so you can put any file in the archive. You can then access that file from your code as long as it is in the classpath. One easy way to do it (but not so clean for big codebases) is to put the file in the same directory structure as your class files.

    To access the file, you can use Class.getResource() as you show, giving a path relative to the class used, and it will be searched using the class loader of the class used. So in your use case, the easiest is probably to put the file in the same directory as the class using the dictionary. For example, in your code is in MyClass, you would write:

    URL dicDic = MyClass.class.getResource("file.dic");
    

    C.f. the javadoc of the method.

    Then to add the files in the jar, this will depend on your workflow and how your build your project (using Eclipse, ant, maven, etc). For example, if you use ant to compile and package your project, there must be somewhere in your build file a jar task that creates the jar file. You should then modify that task to include the dic file in the jar file. In case of doubt, and if you can't find an existing answer, I'd suggest opening a separate question about your particular tool.

    In any case, for the purpose of the test, you can simply open the jar file with Winzip or 7-zip or whatever zip file manager that you use, and add the dic file to the archive.