I am trying to get a JSON file form my resource folder in the main method using relative path. The code works using absolute path but this breaks once I build a jar file from my project which is want I want.
public static void main(String[] args) throws FileNotFoundException {
// Read in database
db = Database.read(Thread.currentThread().getContextClassLoader().getResource("JSON/inhabitants.json").toExternalForm());
names = db.getAllNames();
Read calls a method in Database which uses a inputstream to read the file.
public static Database read(String filename) throws FileNotFoundException {
InputStream is = new FileInputStream(filename);
Reader reader = new InputStreamReader(is);
return gson.fromJson(reader, Database.class);
}
The error I am getting is the following :
java.io.FileNotFoundException: file:/Users/timpelser/IdeaProjects/TurfApp/target/classes/JSON/inhabitants.json (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.(FileInputStream.java:138) at java.io.FileInputStream.(FileInputStream.java:93) at Core.Database.read(Database.java:22) at Main.main(Main.java:51) ... 11 more
The file in directory /Users/timpelser/IdeaProjects/TurfApp/target/classes/JSON/inhabitants.json
does exist however so I have no idea what is going wrong.
Here is my folder structure (Maven basic structure):
Is there a solution which will still able me to deploy it as a jar file ?
EDIT (25/09) : If I use getResourceAsStream instead of getResource, I am getting the following error :
Caused by: java.io.FileNotFoundException: java.io.BufferedInputStream@4f8e5cde (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at Core.Database.read(Database.java:22)
at Main.main(Main.java:51)
... 11 more
您必须使用getResourceAsStream
从正在运行的 jar 中读取文件(其中包含src\\main\\resources
中的文件)!
Use This,
Resource resource = new classpathResource(json);
new ObjectMapper.readValue(resource.getInputStream(),Object.class);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.