[英]How to read files in Java
因此,我需要幫助修復此代碼,或者更多地了解其錯誤。 該代碼本身應該讀取文件並打印出出現的字符串字符串。 但是,即使.txt文件位於我的桌面上,它似乎始終會打印出“找不到文件”。
import java.util.*;
import java.io.*;
/**
* Searcher
*/
public class Searcher extends File {
Scanner scn;
public Searcher(String filename) {
super(filename);
}
public void search(String input) {
try {
scn = new Scanner(this);
String data = "";
while (scn.hasNext()) {
data = scn.nextLine();
}
int count = 0, fromIndex = 0;
while ((fromIndex = data.indexOf(input, fromIndex)) != -1) {
count++;
fromIndex++;
}
System.out.println("Total occurrences: " + count);
scn.close();
} catch (Exception e) {
System.out.println("Cant find file ");
}
}
public static void main(String[] args) {
Searcher search = new Searcher("ihaveadream.txt");
search.search("slavery");
}
}
使用.txt文件的完整路徑,或將其移至項目其余部分所在的文件夾。 該程序不會檢查桌面(即使文件夾位於桌面中)。
您可以使用更優雅的方式通過Stream API讀取文件:
Files.lines(Paths.get(“ / home / userName / Desktop / text.txt”)).forEach(System.out :: println);
根據操作系統的不同,會有不同的路徑,但是文件必須有絕對路徑。
use this code
File file = new File("C:\\Users\\abc\\Desktop\\test.txt");// this is a path of your file
BufferedReader br = new BufferedReader(new FileReader(file));
String str;
while ((str = br.readLine()) != null)
System.out.println(str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.