2015-01-21 55 views
-1

我得到這個例外,當我嘗試從文件讀取:文件未發現後拋出IOException異常

ERROR: 
Exception in thread "main" java.io.FileNotFoundException: newfile.txt (No such file or directory) 
    at java.io.FileInputStream.open(Native Method) 
    at java.io.FileInputStream.<init>(FileInputStream.java:138) 
    at java.util.Scanner.<init>(Scanner.java:611) 
    at Postal.main(Postal.java:19) 


import java.util.Scanner; 
import java.io.*; 

public class Postal { 

    public static void main(String[] args) throws Exception { 
     /*** Local Variables ***/ 
     String line; 
     Scanner filescan; 
     File file = new File("newfile.txt"); 
     filescan = new Scanner(file); 
     userInfo book = new userInfo(); 

     /*** Loop through newfile.txt ***/ 
     while (filescan.hasNext()) { 
      line = filescan.nextLine(); 
      book.addNew(line); 
     } 

     book.print(0); 
    } 

} 
+0

你得到一個運行時異常,而不是一個編譯器錯誤。在類路徑中找不到文件的原因。 – 2015-01-21 00:42:44

+0

@JunedAsan)1)是(2)否,它在當前目錄中不可用* – EJP 2015-01-30 00:24:46

回答

-1

提供您想要創建文件的位置的絕對路徑。並檢查該用戶是否有權在該處創建文件。尋找路徑的一種方法是:

File f = new File("NewFile.txt"); 
if (!f.exists()) { 
    throw new FileNotFoundException("Failed to find file: " + 
     f.getAbsolutePath()); 
} 

嘗試使用此方法打開文件:

File f = new File("/path-to-file/NewFile.txt"); 
+0

您不需要'exists()'檢查。打開文件已經做到了。 – EJP 2015-01-30 00:25:38

+0

@EJP你應該嘗試一下,看看會發生什麼。我很想看到輸出。 – spooky 2015-01-30 00:59:53

0

Scanner使用FileInputStream讀取該文件的內容。 但它找不到該文件,因此引發異常。 您正在使用文件的相對路徑,請嘗試使用絕對路徑。

0

用這個代替:

File file = new File(getClass().getResource("newfile.txt")); 
+0

你可以用這種方式加載文件或者用'file.exists()'處理錯誤。 – 2015-01-21 00:52:32

+0

它工作@ zgangwer20? – 2015-01-21 00:56:00

+0

它不會編譯,因爲getClass()。getResource()需要一個URL,所以不能使用一個字符串。 – zgangwer20 2015-01-21 01:59:46

相關問題