Search code examples
javajarjna

Pass path to text file in Java jar to a C library?


I have a Java jar file that contains a text file. From the Java code within the jar I am using JNA to call functions in a C library. I need to pass a filepath to the text file to one of the C functions, so that the C program can read it.

Since it is the C program and not the Java program that needs to read the file, I can not simply do this:

getClass().getResourceAsStream("MyFile.txt");

The C program is not under my control, and it does not understand a jar:file:// path.

How can this be done? Is the content of the jar automatically extracted somewhere? Do I need to extract it somewhere? How can I do that, when I can not be sure I have writing permissions anywhere?


Solution

  • The file is evidently packed in the jar (or class path): that is meant by resource.

    If you take the URL:

    getClass().getResource("MyFile.txt");
    

    one receives an URL like:

    "jar:file://...path-to-jar... .jar! ...package-path-of-class.../MyFile.txt"
    

    The C part has to unzip that entry from the jar (jar is a zip), and then you are done. Mind the "jar:file:/".

    If the C part cannot be changed, create a temp file

    Path path = Files.createTempFile("temp_", ".txt");
    Files.copy(getClass().getResourceAsStream("MyFile.txt", path));
    

    These functions can have additonal Parameters, file attributes. And pass path.toString().

    Delete it as appropriate.