【问题标题】:filenotfoundexception and file existsfilenotfoundexception 并且文件存在
【发布时间】:2015-02-17 14:28:57
【问题描述】:

我不是第一次在java中使用文件,但这是我第一次使用FileInputStream

我在 resources/backup.txt 中有一个 TXT

然后在我的代码中,当我将文件放入 FileInputStream 构造函数时,它会抛出 FileNotFoundException

这是代码:

public void loadList()  {

    try {

        ArrayList<Partido> myList = Pronosticos.getInstance().getMyList();
        myList.clear();


        File file = new File("resources/backup.txt");
        // create an ObjectInputStream for the file
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));

        // read and print an object and cast it as ArrayList<Partido>
        if (file.length() != 0){
            myList .addAll((ArrayList<Partido>) ois.readObject());
            ois.close();
        }
    } 
    catch (Exception ex) {
        ex.printStackTrace();
    }
}

我不应该从我的 PC 中放置路径,因为我需要它在另一台 PC 上工作。

【问题讨论】:

  • 尝试使用 backup.txt 作为文件名而不是 resources/backup.txt
  • 你能提供堆栈跟踪吗..

标签: java filenotfoundexception fileinputstream


【解决方案1】:

这应该可行。我使用相同的项目设置对此进行了测试:

//note the beginning forward slash
URL url = getClass().getResource("/backup.txt");
File file = new File(url.getPath());

【讨论】:

  • C:\Users\Casa\Downloads\eclipse 是的,这就是工作目录。问题是我需要该程序在另一台计算机上正常工作,所以如果我把那个路径放在我的电脑上,它只会在我的电脑上工作。
  • 更新了我的答案。它与其他答案类似,但添加了您需要的正斜杠
【解决方案2】:

尝试像这样加载文件:

URL url = getClass().getResource("backup.txt");
File file = new File(url.getPath());

并将文件对象传递给FileInputStream

【讨论】:

  • 我得到了 NullPointerException。
猜你喜欢
  • 1970-01-01
  • 2016-01-21
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
相关资源
最近更新 更多