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

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

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

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

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

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

 C:\Users\User\Documents\Workspace\FileRead 

我想知道我做错了什么?

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

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

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

 File file = new File("."); for(String fileNames : file.list()) System.out.println(fileNames); 

看看你是否会在列表中找到你的文件。

通常,仅在文件构造函数中声明文件名称意味着该文件与java文件位于同一目录中。 但是,在使用NetBeans和Eclipse等IDE时,不是必须将文件保存在项目文件夹目录中。 所以我认为检查可以解决您的问题。

在IDE中右键单击要读取的文件,然后选择“复制路径”,然后将其粘贴到代码中。

请注意,windows会隐藏文件扩展名,因此如果您创建文本文件“myfile.txt”,它实际上可能会保存为“myfile.txt.txt”

您需要提供文件存在位置的绝对路径名。

  File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt"); 

你是如何运行该程序的?

它不是正在运行的java文件,而是通过编译java代码创建的.class文件。 您将需要指定user1420750所说的绝对路径或System.getProperty("user.dir")目录的相对路径。 这应该是工作目录或运行java命令的目录。

当你运行一个jar时,你的Main类本身就变成了args [0]并且你的文件名紧随其后。

我遇到了同样的问题:当提供eclipse的绝对路径时,我可以找到我的文件(因为我将文件称为args [0])。 然而,当我从jar运行同样的东西时,它试图找到我的主类 – 这时我才知道我应该从args [1]中读取我的文件。

首先创建与您指定的路径相同的文件夹。 然后创建文件

 File dir = new File("C:\\USER\\Semple_file\\"); File file = new File("C:\\USER\\Semple_file\\abc.txt"); if(!file.exists()) { dir.mkdir(); file.createNewFile(); System.out.println("File,Folder Created.); }