Cristi Ionut
Cristi Ionut

Reputation: 63

Java open file error: can't find the specified path

I try to open a .txt file (agenda.txt) from the src/resources folder, read objects from it and add them to an ArrayList, but I get this error: "The system can not find the specified path.". This is the code I use:

    public void open(File f) {
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    try {
        fis = new FileInputStream(f);
        ois = new ObjectInputStream(fis);
        Object o;
        try {
            while ((o = ois.readObject()) != null) {
                model.adauga((Abonat) o);
            }
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(
                    this,
                    ex.getMessage(),
                    "Clasa...!",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(
                this,
                ex.getMessage(),
                "Eroare deschidere fisier!",
                JOptionPane.ERROR_MESSAGE);
        return;
    } finally {
        try {
            ois.close();
        } catch (IOException ex) {
            Logger.getLogger(CarteDeTelefonGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


}

And in the class constructor:

    private String path ="resources/agenda.txt";
    File f=new File(path);
    open(f);

What is wrong in the code?

Upvotes: 0

Views: 5982

Answers (1)

fGo
fGo

Reputation: 1146

the file should be located outside src, something like baseproject/resources. Thats because your path is the project base not your sources directory. Or you can change the code to

private String path ="src/resources/agenda.txt";

Upvotes: 1

Related Questions