【问题标题】:File not found exception but it is in the same folder/package [duplicate]文件未找到异常,但它位于同一文件夹/包中[重复]
【发布时间】:2017-10-16 15:17:50
【问题描述】:

我有问题。在我的一个包中的程序中有一个 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)

【问题讨论】:

  • 请不要发布错误截图,而是以文本形式发布,即产生错误的代码(除非它太多)和错误本身。
  • 在传入文件时尝试使用文件的绝对路径,而不仅仅是名称
  • 如果我使用绝对路径没问题,但绝对路径是错误的代码,因为如果程序位于其他地方,它会再次抛出此异常。
  • 您正在读取文件。这与包裹无关。相对路径从当前目录开始,即执行 java 命令的目录。就像less foo.txt 读取当前目录下的 foo.txt 文件一样。如果要从类路径加载资源,请不要使用文件 IO。使用Firma.class.getResourceAsStream("Firmendaten.fd")
  • 命令在 Rechnungsprogramm\src\main\Firma.java 执行,应该读取的文件是 Rechnungsprogramm\src\main\Firmendaten.fd 所以在我看来相对路径应该是 Firmendaten.fd

标签: java readfile filenotfoundexception


【解决方案1】:

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

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

【讨论】:

  • 在代码行:String path = Class.class.getProtectionDomain().getCodeSource().getLocation().getPath();如果我使用你的代码 sn-p
  • 我发现了我在使用你的 sn-p 时犯的错误
猜你喜欢
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多