如何获取文件路径

时间:2018-11-21 08:50:44

标签: java

我的Project包(com.test.new)中有test.json文件。

File file = new File("test.json");
            JSONParser parser = new JSONParser();
             JSONObject data = (JSONObject) parser.parse(
                      new FileReader(file.getPath()));//path to the JSON file.
               System.out.println(data.toString());

获取异常:-

Exception in thread "main" java.io.FileNotFoundException: test.json (The system cannot find the file specified)
    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 java.io.FileReader.<init>(FileReader.java:58)

如何获取文件路径位置?

1 个答案:

答案 0 :(得分:1)

这取决于您如何构建和运行应用程序:是否创建jar文件?

构建后,您能否在bin(或等效文件)子目录中检入json文件的位置? 它应该类似于“当前目录”中的com / test / new / test.json。

这样,您便可以通过这种方式轻松获取文件的绝对路径:

File file = new File("com/test/new/test.json");
String path = file.getAbsolutePath();

您可以获得所有文档here

但是,添加安全措施,确保首先存在文件会更安全:

File file = new File("com/test/new/test.json");
if (!file.exists()) {
    // Implement safe-guard ... for instance logging error or throwing an exception
}
相关问题