我正在制作一个打开并读取文件的程序.这是我的代码:
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.java
和hello.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)
并查看您是否会在列表中找到您的文件.
小智 5
您需要将绝对路径名赋予文件所在的位置。
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
Run Code Online (Sandbox Code Playgroud)