MartK
MartK

Reputation: 614

Call a HTML File From Jar

Im generating a report from a template html file in my program. It resides in /src/main/resources and its name is "template.html". Im using ClassLoader inside the code like this:

   private String readTemplateFile() {
        String str = "";
        URL url = ClassLoader.getSystemResource("template.html");

        try {
            FileReader input = new FileReader(url.getFile());
            BufferedReader bufRead = new BufferedReader(input);
            String line;

            line = bufRead.readLine();
            str = line;
            while (line != null) {
                line = bufRead.readLine();
                str += line + "\n";

            }
            bufRead.close();

        } catch (IOException e) {
        }

        return str;
    }

It is doing nicely when you run the code inside IDE but when i make a runnable jar from it, it is generating an empty report. What is the solution? Thanks for reading.

Upvotes: 1

Views: 1983

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

If it's in a jar, it's no longer a file.

Use ClassLoader.getResourceAsStream() to retrieve the resource as an InputStream.

Then convert the InputStream to a String.

Upvotes: 4

Related Questions