Java – If I have a constructor that requires a file path, how can I “fake” if it’s packaged into a jar?

If I have a constructor that requires a file path, how can I “fake” if it’s packaged into a jar?… here is a solution to the problem.

If I have a constructor that requires a file path, how can I “fake” if it’s packaged into a jar?

The context of this issue is that I’m trying to use the MaxMind java API in a pig script I wrote… However, I don’t think knowing any of them is necessary to answer this question.

The maxmind API has a constructor that takes the path to a file named GeoIP.dat, which is a comma-delimited file that contains the required information.

I have a jar file that contains the API, and a wrapper class that instantiates and uses it. The idea is to package GeoIP .dat files into jars and then access them as resources in jar files. The problem is that I don’t know how to construct the path that the constructor can use.

Check out the API, this is how they load files:

public LookupService(String databaseFile) throws IOException {
    this(new File(databaseFile));
}

public LookupService(File databaseFile) throws IOException {
    this.databaseFile = databaseFile;
    this.file = new RandomAccessFile(databaseFile, "r");
    init();
}

I

only paste it because I’m not averse to editing the API itself to make it work if necessary, but don’t know how to replicate a feature like mine. Ideally, though, I’d like to put it in a file form, otherwise editing the API would be a hassle.

Is this possible?

Solution

Try:

new File(MyWrappingClass.class.getResource(<resource>).toURI())

Related Problems and Solutions