【问题标题】:Exception in thread "main" java.io.FileNotFoundException: java.io.BufferedInputStream@73035e27 (The system cannot find the file specified) [closed]线程“main”中的异常java.io.FileNotFoundException:java.io.BufferedInputStream@73035e27(系统找不到指定的文件)[关闭]
【发布时间】:2021-02-26 13:09:30
【问题描述】:

我必须从 git 中的 \\resource 文件中读取外部文件。我必须使用资源文件夹,因为我与其他人共享项目,所以我们的 trainingData 文件的路径会有所不同。我写道:

public static String trainingFile = Trainer.class.getClassLoader().getResourceAsStream("trainingData.txt").toString();

然后trainingFile必须被阅读,我写道:

FileInputStream fstream = new FileInputStream(trainingFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
while ((strLine = br.readLine()) != null)   
{
    fileNames.add(strLine);
}

当我运行它时,它给了我错误: Exception in thread "main" java.io.FileNotFoundException: java.io.BufferedInputStream@73035e27 (The system cannot find the file specified) 到“FileInputStream fstream”行。 非常感谢您的帮助。

【问题讨论】:

  • 你看过trainingFile的值了吗?如果没有,做。为什么你认为它有这个价值?

标签: java string file exception inputstream


【解决方案1】:

其实trainingFile 不是输入流和文件路径。你可以这样做:

InputStream trainingFile = Trainer.class.getClassLoader().getResourceAsStream("trainingData.txt");

    List<String> fileNames = new ArrayList<String>();
    BufferedReader br = new BufferedReader(new InputStreamReader(trainingFile));
    String strLine;
    while ((strLine = br.readLine()) != null)
    {
        fileNames.add(strLine);
        System.out.println(strLine);
    }

【讨论】:

    【解决方案2】:

    Trainer.class.getClassLoader().getResourceAsStream("trainingData.txt").toString() 将返回一个类似于java.io.BufferedInputStream@7b1d7fff 的字符串,这不是您应该传递给FileInputStream 的参数,它需要路径名。

    您可以将InputStream 传递给InputStreamReader,如下所示:

    InputStream trainingFile = Trainer.class.getClassLoader().getResourceAsStream("trainingData.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(trainingFile));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      相关资源
      最近更新 更多