2017-10-16 158 views
0

我有一個問題。在我的程序中,有一個類Firma。 在這個類的構造函數中,我從名爲'firmendaten.fd'的文本文件中讀取了一些信息。該文本文件也位於相同的包,但如果我嘗試閱讀我得到FileNotFoundException文件未發現異常,但它是在同一文件夾/包

產生錯誤的代碼:

public Firma(){ 
    BufferedReader in = null; 
    try { 
     in = new BufferedReader(new FileReader("Firmendaten.fd")); 
     name = in.readLine(); 
     zusatz = in.readLine(); 
     strasse = in.readLine(); 
     hnr = in.readLine(); 
     plz = in.readLine(); 
     ort = in.readLine(); 
     bank = in.readLine(); 
     iban = in.readLine(); 
     bic = in.readLine(); 
     steuerNr = in.readLine(); 
     steuersatz = in.readLine(); 
     chef = in.readLine(); 
     zahlungsziel = in.readLine(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (in != null) 
      try { 
       in.close(); 
      } catch (IOException e) { 
      } 
    } 
    } 

錯誤它產生:

java.io.FileNotFoundException: Firmendaten.fd (Das System kann die angegebene Datei nicht finden) 
at java.io.FileInputStream.open0(Native Method) 
at java.io.FileInputStream.open(Unknown Source) 
at java.io.FileInputStream.<init>(Unknown Source) 
at java.io.FileInputStream.<init>(Unknown Source) 
at java.io.FileReader.<init>(Unknown Source) 
+1

請不要發佈錯誤的截圖,但以文本形式張貼,即產生錯誤(除非它是太多)代碼和錯誤本身。 – Thomas

+0

嘗試使用,當你經過它,而不是僅僅名稱 –

+0

如果我使用絕對路徑它的優良的文件的絕對路徑,但絕對路徑是錯誤代碼,因爲如果PROGRAMM位於其他地方再次拋出該異常。 – flam3shadow

回答

0

我最近也有類似的十歲上下的問題,所以我使用的.jar文件的位置,其中該程序正在運行。

 String path = Class.class.getProtectionDomain().getCodeSource().getLocation().getPath(); 
     path = path.substring(0, path.lastIndexOf("/") + 1); 
     String decodedPath = URLDecoder.decode(path, "UTF-8"); 
     return decodedPath; 

那時,我便像文件:

File file = new File(userPath + "\\yourfile.txt"); 

注意,這是從這裏回答的混合服用,所以希望可以幫助你。

+0

在程序代碼:。 字符串路徑= Class.class.getProtectionDomain()getCodeSource()的getLocation()的getPath(); 如果我用你的代碼片段 – flam3shadow

+0

我發現我在使用片斷犯的錯 – flam3shadow

相關問題