从 Jar 调用 HTML 文件

发布于 2024-10-02 11:55:05 字数 791 浏览 0 评论 0原文

我从程序中的模板 html 文件生成报告。它位于 /src/main/resources 中,名称为“template.html”。我在代码中使用 ClassLoader,如下所示:

   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;
    }

当您在 IDE 中运行代码时,它运行得很好,但是当我从中创建一个可运行的 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

混吃等死 2024-10-09 11:55:05

如果它在 jar 中,则它不再是文件。

使用 类加载器.getResourceAsStream()InputStream 形式检索资源。

然后将InputStream转换为字符串

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文