0

I'm doing a Java project in Eclipse. I am using some relative paths such as:

File htmlTemplateFile = new File("src/templateGeno2Pheno.html");

instead of absolute paths:

File htmlTemplateFile = new File("/Users/.../Documents/workspace/SeqAnalysis/src/templateGeno2Pheno.html");

Everything works very well when I run it with Eclipse, but once I export it to a runnable JAR and execute it, it doesn't work.

This is my folder structure: enter image description here

Here is my code: enter image description here

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

0

After packaging into a JAR then everything, including your HTML templates, are zipped up into that JAR and therefore filesystem paths aren't going to work for you. Java doesn't have a file addressing system like your browser/html.

One option is to load those html templates using ClassLoader.getResourceAsStream API.

Change your code to:

InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/templateGeno2Pheno.html");
String htmlString = IOUtils.toString(stream);

IOUtils is from the Apache Commons IO library.

HTH

Paul Warren
  • 2,411
  • 1
  • 15
  • 22
  • Hi, ok I understand now, but I still have an error after changing the lines: https://i.stack.imgur.com/CMfUv.png – user9903821 Jun 07 '18 at 09:20
  • An empty stream? Or null? An empty stream would indicate that the path /templateGeno2Pheno.html is correct but the file is empty. Null would indicate that the path is not quite right. I cant remember exactly how the addressing works. You could try just `templateGeno2Pheno.html` – Paul Warren Jun 09 '18 at 16:44
  • Updated answer to use `ClassLoader.getResourceAsStream`. Try using that. ClassLoader.getResourceAsStream will interpret the `/templateGeno2Pheno.html` path as absolute from the root of your src folder (i.e. classpath) whereas `Class.getResourceAsStream` interprets it as relative from where the class lives. See this SO: https://stackoverflow.com/questions/676250/different-ways-of-loading-a-file-as-an-inputstream – Paul Warren Jun 09 '18 at 16:51