2016-11-28 57 views
-1

當我爲「搜索」輸入完整的文件路徑(C:\ Users \ djustinwebb \ Documents \ BlueJ Projects \ LightHouse)時,它試圖打開文件,我得到錯誤: java.io.FileNotFoundException:C:\ Users \ djustinwebb \ Documents \ BlueJ Projects \ LightHouse(訪問被拒絕)(在java.io.FileInputStream中)如何避免此java.io.FileNotFoundException?

我輸入「invoicedata.txt」進行搜索,即使它沒有讀取文件正確,但我想知道爲什麼當我使用完整的文件路徑時不起作用。我需要做什麼來使用完整的文件路徑而不會遇到這個錯誤?

public String searchCase()throws FileNotFoundException 
{ 
    String fileLine = null; 

    StringTokenizer stok = null; 

    Scanner inputFile = new Scanner(new File(search)); 


    String whatever = null; 



    while(inputFile.hasNextLine()) 
    { 
     fileLine = inputFile.nextLine(); 
     stok = new StringTokenizer(fileLine,","); 

     caseLCount++; 

     while(stok.hasMoreTokens()) 
     { 
      if(userWord.equals(stok.nextToken())) 
      { 
       caseWCount++; 

       whatever += caseLCount + ".\n"; 
      }//end if 
     }// end nested while 
    }//end outer while 
    inputFile.close(); 
    return whatever; 
}// end searchCase() 
+0

該文件是否真的存在於該路徑?你可以從另一個程序打開文件嗎?嘗試以管理員模式運行Java進程。 –

+0

似乎是權限問題。它拒絕訪問的事實意味着它確實嘗試打開文件 – Mox

回答

3

這是因爲你試圖打開和讀取directory,這是LightHouse這裏。您應該在文件路徑中輸入文件名,例如..\LightHouse\invoicedata.txt

如果要區分文件和文件夾,請使用isFile()isDirectory()方法。您可以使用list()listFiles()方法獲取文件夾的內容。