系统找不到java中指定的文件

gad*_*dss 20 java file

我正在制作一个打开并读取文件的程序.这是我的代码:

import java.io.*;

public class FileRead{
    public static void main(String[] args){
        try{
            File file = new File("hello.txt");
            System.out.println(file.getCanonicalPath());
            FileInputStream ft = new FileInputStream(file);

            DataInputStream in = new DataInputStream(ft);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strline;

            while((strline = br.readLine()) != null){
                System.out.println(strline);
            }
            in.close();
        }catch(Exception e){
            System.err.println("Error: " + e.getMessage());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是当我跑步时,我收到这个错误:

C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)
Run Code Online (Sandbox Code Playgroud)

FileRead.javahello.txt在同一目录中的位置可以找到:

C:\Users\User\Documents\Workspace\FileRead
Run Code Online (Sandbox Code Playgroud)

我想知道我做错了什么?

Eng*_*uad 46

尝试通过调用列出目录中的所有文件名称:

File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
Run Code Online (Sandbox Code Playgroud)

并查看您是否会在列表中找到您的文件.


Adr*_*hum 9

我复制了你的代码,运行正常.

我怀疑你在hello.txt的实际文件名中遇到了一些问题,或者你在错误的目录中运行.请考虑通过@ Eng.Fouad建议的方法进行验证


小智 5

您需要将绝对路径名赋予文件所在的位置。

        File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
Run Code Online (Sandbox Code Playgroud)