找不到文件异常,但它在同一个 folder/package

File not found exception but it is in the same folder/package

我有问题。在我的程序包中有一个class Firma。 在这个 class 的构造函数中,我从名为 '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)

我最近遇到了类似的问题,所以我使用了程序所在的 .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");

请注意,这是从此处的混合答案中提取的,因此希望对您有所帮助。