0

I am trying to create a runnable jar file. My project includes models.txt file. My project works perfectly in eclipse with no error but when exported to a runnable jar file, It doesn't work. I hereby attach the error and the piece of code where the file is been called.

public static HashMap<String, RenderModel>  getModelList(String file) throws IOException {
    List<String> data;
    HashMap<String, RenderModel> namesToModels = new HashMap<String, RenderModel>();

    if (file != null) {
        data = Files.readAllLines(Paths.get(file), StandardCharsets.UTF_8);
    } else {
        String path = "models/models.txt";
        data = Files.readAllLines(Paths.get(path),  StandardCharsets.UTF_8);
    }

    Iterator<String> dataIterator = data.iterator();
    while (dataIterator.hasNext()) {
        String dataLine = dataIterator.next();
        System.out.println(dataLine);
        String[] line = dataLine.split("; ");
        String key = line[0];
        String valueObj = line[1];
        String valueMtl = line[2];
        float scale = Float.parseFloat((String) line[3]);
        RenderModel v = new RenderModel(valueObj, valueMtl, scale);
        namesToModels.put(key, v);
    }
    RenderModel v =  new RenderModel("custom", "custom", 1.0f);
    namesToModels.put("Choose Model from file", v);
    return namesToModels;
}

Error Image:

Error Image

DimaSan
  • 12,264
  • 11
  • 65
  • 75
Ankit1016
  • 33
  • 1
  • 6

3 Answers3

1

If the files are in the Jar and you cannot read them, try accessing the files by doing:

getClass().getClassLoader().getResource(fileName);

Use this instead for static methods:

ClassName.class.getClassLoader().getResource(fileName);

Where fileName is the name of the file and ClassName the name of the class from which the statement is called.

nick zoum
  • 7,216
  • 7
  • 36
  • 80
0

In your code the path of the model.txt is 'src/models/model.txt'. When your project is packaged the src folder is not included usually. Then you must change the file location; could be better put the file outside the jar, but inside the java classpath.

0

It does not work because you do not have any file on the path src/models/models.txt when you run your jar else where, this path is only present in your IDE (ofcourse you can place your jar in a location from where it can reach that path, but this is not how it is supposed to be), when you package your project into a jar file it is packed in the package models and you can if you want to have it as default file read it via classpath.

Community
  • 1
  • 1
A4L
  • 17,353
  • 6
  • 49
  • 70