简体   繁体   English

Java异常错误I / O

[英]Java Exception error i/o

I am getting an error when I try to read my file abc.txt in my D drive. 尝试读取D盘中的文件abc.txt时出现错误。 Even I tried format : "D:\\EDU\\java\\abc.txt" 即使我尝试了格式:“ 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 1)更改代码如下

 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. 您必须从InputStream读取数据。

EDIT : Resolve non static error 编辑 :解决非静态错误

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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