2017-04-04 70 views
-1

由於某種原因FileReader無法找到我指定的文件"read1.json"。我嘗試了許多事情,將名稱更改爲更改位置,但與文件本身無關。我想知道爲什麼它找不到該文件。FileReader找不到文件

Error:(13, 35) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

Error:(13, 34) java: unreported exception java.io.IOException; must be caught or declared to be thrown

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); 
    } 
} 
+0

該路徑中是否存在read1.json文件? – leoOrion

+0

'FileReader找不到我指定的文件「read1.json」 - 不,這不是編譯器告訴你的。編譯器告訴你,如果你想編譯程序,你需要處理'FileNotFoundException'。 – BackSlash

+0

如果向此代碼添加try-catch塊,並在捕獲異常時進行調試,那麼異常說明了什麼? – Detilium

回答

1

FileReader cannot find the file I specified "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); 

} 
+0

請問爲什麼我需要使用try catch塊?我試過你的代碼,它給了我另一個錯誤:錯誤:(16,38)java:unreported exception org.json.simple.parser.ParseException;必須被捕獲或聲明爲拋出 – Vitalynx

+0

@Vitalynx對於'ParseException'來說,同樣的事情,你需要一個catch塊。有關異常的問題,請參閱[官方指南](http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html) – BackSlash

0

ü需要使用try-catch塊來處理FileNotFound因爲它是檢查異常。並且它必須在編譯時檢查。編譯器會拋出這個錯誤,因爲這可能是運行時的可能異常,因此它建議您在實際發生之前處理它。

+0

編譯器不會拋出它,編譯器檢查它是否處理。異常會在運行時拋出,而不是在編譯時 – BackSlash

+0

我的意思是說這個錯誤消息編譯器會給出: 錯誤:(13,35)java:unreported exception java.io.FileNotFoundException;必須被捕或被宣佈爲拋出 不例外我在談論這個錯誤信息。 – yuvrajK

+0

是的,這是編譯時錯誤,不是拋出的異常 – BackSlash