Java 如何获取项目中的文件位置?
我目前正在使用一个JSON文件,即products.JSON来编写关键字搜索应用程序。我将文件放入包com.search.api.dao中,如图所示 我使用以下代码读取ProductsDAO.java类的构造函数中的数据Java 如何获取项目中的文件位置?,java,eclipse,file-io,Java,Eclipse,File Io,我目前正在使用一个JSON文件,即products.JSON来编写关键字搜索应用程序。我将文件放入包com.search.api.dao中,如图所示 我使用以下代码读取ProductsDAO.java类的构造函数中的数据 public ProductsDAO() throws FileNotFoundException, IOException, ParseException { JSONParser parser = new JSONParser(); URL path =
public ProductsDAO() throws FileNotFoundException, IOException, ParseException {
JSONParser parser = new JSONParser();
URL path = ProductsDAO.class.getResource("products.json");
File myFile = new File(path.getFile());
Object obj = parser.parse(new FileReader(myFile));
JSONObject js = (JSONObject) obj;
jsonArray = (JSONArray) js.get("products");
}
如您所见,我在src中创建了data文件夹,并将products.json文件放在那里。这里的完整位置路径是“/ProductSearch/src/data/products.json”。如何从该位置读取文件?我尝试了相对路径和绝对路径,但没有一条不起作用
URL path=ProductsDAO.class.getResource(“/data/products.json”)
或URL path=ProductsDAO.class.getResource(“data/products.json”)
。不要在你的路径中包含src
,无论如何,非常感谢,这很好用。