Java异常错误i / o

时间:2015-10-18 16:08:20

标签: java exception-handling ioexception runtimeexception

当我尝试在D驱动器中读取文件abc.txt时出错。 即使我尝试格式化:“D:\ EDU \ java \ abc.txt”

这是我的代码:

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

我的错误:

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)

3 个答案:

答案 0 :(得分:1)

确保该文件实际位于该目录中。右键单击并单击“属性”以检查路径。

如果您已完成此操作,请将所有\更改为/\\

答案 1 :(得分:1)

错误不言自明。该文件不是您告诉应用程序的位置。检查您的路径以确保它指向该文件。

答案 2 :(得分:0)

1)更改代码如下

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

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

//if abc.txt is present in classpath

从InputStream,您必须读取数据。

编辑:解决非静态错误

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