FileReader无法找到文件

时间:2017-04-04 11:30:39

标签: java

由于某种原因,FileReader无法找到我指定的文件"read1.json"。我尝试了很多东西,将名称更改为更改位置,但它与文件本身无关。我想知道为什么它找不到该文件。

  

错误:(13,35)java:unreported exception java.io.FileNotFoundException;必须被抓住或宣布被抛出

     

错误:(13,34)java:unreported exception java.io.IOException;必须被抓住或宣布被抛出

import jdk.nashorn.api.scripting.URLReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import java.io.FileReader;

public class Main {

public static void main(String[] args) {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader("C:\\Users\\Home\\Documents\\read1.json"));

    JSONObject jsonObject = (JSONObject) obj;
    System.out.println(jsonObject);
  }
}

2 个答案:

答案 0 :(得分:1)

  

FileReader找不到我指定的文件“read1.json”

没有。这不是编译器告诉你的。如果要编译程序,编译器会告诉您需要同时处理FileNotFoundExceptionIOException

使用try-catch块:

try {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader("C:\\Users\\Home\\Documents\\read1.json"));

    JSONObject jsonObject = (JSONObject) obj;
    System.out.println(jsonObject);
} catch (FileNotFoundException e) {
    // handle file not found
} catch (IOException e) {
    // handle ioexception
}

或者添加throws子句(在这种特定情况下设计不好):

public static void main(String[] args) throws FileNotFoundException, IOException {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader("C:\\Users\\Home\\Documents\\read1.json"));

    JSONObject jsonObject = (JSONObject) obj;
    System.out.println(jsonObject);

}

答案 1 :(得分:0)

你需要使用try-catch块来处理FileNotFound异常,因为它被检查异常。并且必须在编译时检查。编译器抛出此错误,因为这可能是运行时的可能异常,因此它建议您在实际发生之前处理它。