Question

Sorry for the bad title, can't think of a better one.

I am currently in this contradicting problem with FileNotfoundException where my file is located via a command file.getCanonicalPath() and when using the FileInputStream method. I get a FileNotFoundException.

Below are the codes I used:

File file = new File("members.s");
        System.out.println(file.getCanonicalPath());

        FileInputStream fileIn = new FileInputStream("C:\\Users\\users\\Documents\\NetBeansProjects\\CWA2\\members.s");
        ObjectInputStream in = new ObjectInputStream(fileIn);

        byte[] b=new byte[fileIn.available()];
        for(int i=0;i<b.length;i++){
            m.add(mem = (Member)in.readObject());
        }

This is the output and exception errors I get.

    C:\Users\users\Documents\NetBeansProjects\CWA2\members.s
java.io.FileNotFoundException: C:\Users\users\Documents\NetBeansProjects\CWA2\members.s (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileInputStream.<init>(FileInputStream.java:101)
    at Demos.DeserializeDemo.main(DeserializeDemo.java:21)

So I am abit confused. How is it that the file.getCanonicalPath() method can locate the file I want to use, but the FileInputStream returns an error. Can anyone help me on thiS?

Était-ce utile?

La solution

file.getCanonicalPath() would just return "members.s" as its path and not the full path. getCaninicalPath() removes redundant . or .. from the pathname.

Because FileInputStream takes File as its argument (also a string btw) and File takes a String as argument.

File file = new File("members.s");
System.out.println(file.getCanonicalPath());

FileInputStream fileIn = new FileInputStream("C:\\Users\\users\\Documents\\NetBeansProjects\\CWA2\\members.s");

This should be

File file = new File("C:\\Users\\users\\Documents\\NetBeansProjects\\CWA2\\members.s");
FileInputStream fileIn = new FileInputStream(file);

Autres conseils

This exception will be thrown, when a file with the specified pathname does not exist or if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top