简体   繁体   中英

Get path of binary file within a JAR file

I have a jar file when unzipped looks like the following:

models/
com/
com/github/
com/github/
com/github/test/linux-x86_64/
com/github/test/config/
models/model.bin   
com/github/test/Test.class   

In the Test class, I'm using the path of model.bin inside the getResults method like so:

public class Test {

      public List<Label> getResults(String text, int k) {

        // Load model from file
        loadModel("models/model.bin");

        // Do label prediction
        return results(text, k);
    }

} 

The loadModel method above is actually c++ method that looks like this. I am writing a Java Wrapper around a c++ library:

void Testtext::loadModel(const std::string& filename) {

  std::ifstream ifs(filename, std::ifstream::binary);
  if (!ifs.is_open()) {
    throw std::invalid_argument(filename + " cannot be opened for loading!");
  }
  if (!checkModel(ifs)) {
    throw std::invalid_argument(filename + " has wrong file format!");
  }
  loadModel(ifs);
  ifs.close();
}

Currently, when I run this from an IDE, I get an error that says the model.bin file cannot be found. How do I determine the path of the model.bin within a jar file?

It sounds like whatever loadModel is (it is not part of standard java, so you'd have to elaborate) requires an actual file. Which your model.bin resource isn't (it's an entry in a jar).

Check if loadModel has an InputStream based method. It really should; if it doesn't, whatever library this is, does not follow java conventions, and is probably badly written.

If it does:

try (InputStream in = Test.class.getResourceAsStream("/models/model.bin")) {
    loadModel(in);
}

will do the trick.

If it doesn't, oh boy. Either fix loadModel yourself, ask its authors to fix it, or if you must work around it, your only option is to copy the resource into an actual file, presumably in a temp dir, and then use that temporary file. This isn't pretty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM