简体   繁体   中英

Java Exception error i/o

I am getting an error when I try to read my file abc.txt in my D drive. Even I tried format : "D:\\EDU\\java\\abc.txt"

Here's my code :

package javapro;

import java.io.FileInputStream;

public class office {

    public static void main (String[] args)throws Exception {
        FileInputStream apple = new FileInputStream ("D:/EDU/java/abc.txt");
        int din;
        while ((din=apple.read())!=-1){
            System.out.println((char)din);
        }
        apple.close();
    }
}

My Error :

Exception in thread "main" java.io.FileNotFoundException: D:\EDU\java\abc.txt (The system cannot find the file specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at javapro.office.main(office.java:8)

Make sure the file is actually located in that directory. Right-click and click on Properties to check the path.

If you've done that, change all the \\ to / or \\\\ .

The error is self-explanatory. The file isn't where you have told the application it is. Check your path to make sure that it leads to the file.

1) Change the code as below

 FileInputStream apple = new FileInputStream ("D:\\EDU\\java\\abc.txt");

or

 InputStream is = getClass().getResourceAsStream("abc.txt");

//if abc.txt is present in classpath

From InputStream, you have to read the data.

EDIT : Resolve non static error

InputStream is = office.class.getClass().getResourceAsStream("abc.txt");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM