Java fileNotFound\NullPointerExcetion尝试解析json时出错
我正在做一个maven项目,我正在尝试使用Gson或simpleJson作为我项目的解析器 我的资源文件夹中有一个名为moves.json的文件 当我试图运行此代码时:Java fileNotFound\NullPointerExcetion尝试解析json时出错,java,json,maven,parsing,gson,Java,Json,Maven,Parsing,Gson,我正在做一个maven项目,我正在尝试使用Gson或simpleJson作为我项目的解析器 我的资源文件夹中有一个名为moves.json的文件 当我试图运行此代码时: JSONParser pr = new JSONParser(); Object el = pr.parse(new InputStreamReader(new FileInputStream("moves.json"))); JsonReader reader = new JsonReader(new InputStre
JSONParser pr = new JSONParser();
Object el = pr.parse(new InputStreamReader(new FileInputStream("moves.json")));
JsonReader reader = new JsonReader(new InputStreamReader(test.class.getResourceAsStream("moves.json")));
JsonElement movelist = new JsonParser().parse(reader);
我得到一份工作
Exception in thread "main" java.io.FileNotFoundException: moves.json (No such file or directory)
当我尝试这个代码时:
JSONParser pr = new JSONParser();
Object el = pr.parse(new InputStreamReader(new FileInputStream("moves.json")));
JsonReader reader = new JsonReader(new InputStreamReader(test.class.getResourceAsStream("moves.json")));
JsonElement movelist = new JsonParser().parse(reader);
我得到一个:
Exception in thread "main" java.lang.NullPointerException
我尝试使用ClassLoader和getResource以及我在web上搜索的其他方法,但我得到了与null指针异常相同的错误
这是完整的课程:
import com.google.gson.*;
import com.google.gson.stream.JsonReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.*;
public class test {
public static void main(String [] args) throws IOException, ParseException {
JSONParser pr = new JSONParser();
Object el = pr.parse(new InputStreamReader(new FileInputStream("moves.json")));
JsonReader reader = new JsonReader(new InputStreamReader(test.class.getResourceAsStream("moves.json")));
JsonElement movelist = new JsonParser().parse(reader);
System.out.println("");
}
}由于资源位于类路径上,您应该使用类加载机制打开流:
Object el = pr.parse(new InputStreamReader(
test.class.getResourceAsStream("moves.json")));
这似乎与所有其他类似问题相同,解决方案是将文件路径更改为Java正在查找的位置。你有没有在这个网站上查看过类似的问题,因为你会发现很多。请查看并查看更多关于查找资源的信息。我查看了类似的问题,但没有一个因为某种原因对我有所帮助,我设法找到了答案,谢谢。正如其他人所说,Java所看到的路径不是你期望它看到的路径。因此,您的路径是错误的,Java找不到该文件。通过打印来检查路径。例如
System.out.println(path.get().toabsolutionPath())代码>。这是java在编写newFileInputStream(“moves.json”)时看到的相对路径的开始代码>。它可能不是你期望的地方。相应地调整路径,它就会起作用。我们是否应该回答明显重复的问题?“moves.json”不起作用,但“/moves.json”起作用,谢谢you@eyalmazuztest
是否在包中(非默认)?yes测试是否在包中package@eyalmazuz这就是为什么需要“/moves.json”
(你的问题没有包括类的包
声明,所以我假设)