【问题标题】:Not able read json file loacted in app's resource folder on azure无法读取位于 Azure 上应用程序资源文件夹中的 json 文件
【发布时间】:2019-03-06 18:34:05
【问题描述】:

我有 Spring Boot 应用程序。我正在尝试读取位于我的资源文件夹中的 json 文件(使用类加载器)。我已经在 azure 上部署了我的应用程序,它给了我错误,没有这样的文件存在,当我打印路径时它给我 null。

【问题讨论】:

  • 能否添加加载文件的代码(连同路径)?
  • classLoader = getClass().getClassLoader();文件 file = new File(URLDecoder.decode(classLoader.getResource("tags.ser").getFile()));

标签: java spring azure spring-boot


【解决方案1】:

我尝试创建一个简单的 Maven 项目来解决您的问题。

我的源代码结构如下。

simpleMavenProj
   |-src/main/java/Hello.java
   |-src/main/resources/hello.json

Hello.java的内容如下。

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

public class Hello {

    public static void main(String[] args) throws IOException {
        InputStream resourceInputStream = null;
        URL resourceURL = Hello.class.getClassLoader().getResource("resources/hello.json");
        if(resourceURL == null) {
            System.out.println("Get the InputStream of hello.json in IDE");
            resourceInputStream = new FileInputStream(Hello.class.getClassLoader().getResource("").getPath()+"../../src/main/resources/hello.json");
        } else {
            System.out.println("Get the InputStream of hello.json from runnable jar");
            resourceInputStream = Hello.class.getClassLoader().getResourceAsStream("resources/hello.json");
        }
        System.out.println();
        StringBuilder builder = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(resourceInputStream));
        String line = null;
        while((line = br.readLine()) != null) {
            builder.append(line+"\n");
        }
        br.close();
        System.out.println(builder.toString());
    }
}

还有hello.json:

{
    "hello":"world"
}

如果你是在IDE中开发,运行代码,结果是:

Get the InputStream of hello.json in IDE

{
    "hello":"world"
}

否则生成一个可运行的jar文件,然后通过java -jar simpleMavenProj.jar运行jar文件,结果为:

Get the InputStream of hello.json from runnable jar

{
        "hello":"world"
}

希望对您有所帮助。有任何问题,请随时告诉我。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 2023-03-24
    • 1970-01-01
    • 2021-12-31
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多