Search code examples
javafilenotfoundexceptionfileinputstream

filenotfoundexception and file exists


is not the first time that I use files in java, but it is the first time that I use FileInputStream.

I have a TXT in resources/backup.txt

enter image description here

Then in my code, when I put the file in the FileInputStream constructor it throws a FileNotFoundException.

This is the code:

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();
    }
}

I should not put the Path from my PC because I need it to work in another PC.


Solution

  • This should work. I tested this with the same project setup:

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