我有Spring Boot应用。我正在尝试读取位于我的资源文件夹(使用类加载程序)中的JSON文件。我已经在Azure上部署了我的应用程序,这给我带来了错误,没有这样的文件,当我打印路径时,它给了我无效。
我试图创建一个简单的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"
}
希望它有帮助。任何问题,请随时让我知道。