Search code examples
javareadfilefilenotfoundexception

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


I have a problem. In my program in one package there are a class Firma. At the constructor of this class I read some information out of a text file named 'firmendaten.fd'. The textfile is also located at the same package, but if I try to read i get a FileNotFoundException.

The code which produces the error:

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) { 
            } 
    } 
    }

The error it produces:

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)

Solution

  • I had a similar-ish problem recently so I used the location of the .jar file of which the program was running.

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

    Then I called the file like:

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

    Note that this was taken from a mix of answers on here, so hopefully may help you.