【问题标题】:I am getting file does not exist exception我得到文件不存在异常
【发布时间】:2019-08-25 00:58:21
【问题描述】:

我正在设置将字符串写入 html 文件的逻辑

我尝试阅读位于 \src\main\resources\static\ 中的 details.html 文件

File htmlTemplateFile = new File("details.html");

File htmlTemplateFile = new File("\src\main\resources\static\details.html");

当我运行此代码时,我得到了 file not found 异常,尽管该文件位于 \src\main\resources\static\

我已经尝试了上述两种方法,仍然抛出未找到文件的异常。

错误:msgjava.io.FileNotFoundException:文件“details.html”不存在

【问题讨论】:

  • 您需要绝对路径(来自根目录)或相对路径(来自执行上下文),您都没有。如果你想将它作为 resource 打开,那么你应该这样做,并且路径将相对于类路径。
  • 我正在探索新鲜的java,很抱歉有疑问但是,我在哪里可以找到我的相对路径? @戴夫牛顿
  • 尝试new File("static/details.html"); /resources 下的所有内容都被视为类路径条目。

标签: spring spring-boot jakarta-ee file-io


【解决方案1】:

Spring Boot 将自动添加位于其中的静态 Web 资源 以下任一目录:

/META-INF/资源/
/资源/
/静态/
/公共/

来自How can I serve static html from spring boot?

所以以下工作(测试):

@SpringBootApplication
public class StackoverflowApplication implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(StackoverflowApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {


        // index.html under /src/main/resources/static
        File file = new File("index.html");

        System.out.println(file.getName());

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多