[英]What's wrong with this code in java that uses FileReader?
我一直在努力學習FileReader
,因此想要測試它。 我創建了一個類,其構造函數接受一個字符串(文件的名稱)並創建一個文件然后從中讀取然后打印出第一個字符,但我的代碼不起作用並顯示錯誤。 這是我的java代碼。
package test_3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Files {
public Files(String s) throws FileNotFoundException, IOException{
File f = new File(s);
FileReader fr = new FileReader(f);
System.out.println(fr.read());
}
public static void main(String args[]) throws FileNotFoundException, IOException{
Files myFile = new Files("input.txt");
}
}
這是錯誤信息
Exception in thread "main" java.io.FileNotFoundException: input.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.FileReader.<init>(Unknown Source)
at test_3.Files.<init>(Files.java:11)
at test_3.Files.main(Files.java:16)
因為無法找到該文件。 你應該做的是獲取java尋找文件的路徑,就像這樣。
System.out.print(System.getProperty("user.dir"));
然后將“input.txt”放在該目錄(運行該代碼時打印的目錄)中。
或者,使用input.txt的完整絕對路徑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.