2015-11-14 172 views
-1

如何捕獲文件對象返回的空引用null?我不斷收到java.lang.NullPointerException拋出java.lang.NullPointerException異常

public static File getFile() { 
     String filePath = JOptionPane.showInputDialog("Enter the full path to   the file you want to open"); 
     File file = new File(filePath); 
     while(!file.exists()) { 
      filePath = JOptionPane.showInputDialog("Please enter a valid full path"); 
     } 
     return file; 
    } 
} 
+0

你應該以可讀格式 – 3kings

+0

格式化你的代碼之前,你需要創建文件正確嗎?如果它不存在 – 3kings

+3

要回答你的問題:[TryCatch](https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html)。但是,這實際上不是你想要處理它的方式。你可能想用一個簡單的if來檢查'null'。 – Emz

回答

0

的javadoc約public File(String pathname)構造:

NullPointerException - If the pathname argument is null 

所以最好先檢查一下filePathnull,把它傳遞給new File(String path)