문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top