Java讀寫檔案,在檔案中搜索內容,並輸出含有該內容的所有行
阿新 • • 發佈:2018-11-30
1.問題描述
在一個目錄及子目錄下查詢 TXT或Java檔案,從中搜索所有“物件”字樣的行。
在D盤中的所有檔案中搜索含有“物件”的行。
2.解題思路
先找出D盤下所有檔案
再對每個檔案中的每行內容進行,進行查詢,若含有“物件”兩字,輸出該行。
3.程式程式碼
import java.io.File; import java.io.IOException; import java.util.Scanner; public class B { static int m=1; static void search(File a,String x) throws IOException{//在檔案a中的每行中查詢x Scanner scan = new Scanner(a,"gbk"); int k = 0; while(true){ if(scan.hasNext()==false) break; String s = scan.nextLine(); k++; if(s.contains(x)){ String ss =m +".檔案:"+ a.getPath() + " 第" + k + "行 \n 內容:" + s; System.out.println(ss); m++; } } Scanner scan1 = new Scanner(a,"utf-8"); int k1 = 0; while(true){ if(scan1.hasNext()==false) break; String s1 = scan1.nextLine(); k1++; if(s1.contains(x)){ String ss1 =m +".檔案:"+ a.getPath() + " 第" + k1 + "行 \n 內容:" + s1; System.out.println(ss1); m++; } } } static void f(File a,String s)throws IOException{//在a下所有檔案中查詢含有s的行 File[] ff = a.listFiles(); if(ff==null) return; for(File it : ff){ if(it.isFile()){//若a是檔案,直接查詢 search(it,s); } if(it.isDirectory()){//若a是目錄,則對其目錄下的目錄或檔案繼續查詢 f(it,s); } } } public static void main(String[] args)throws IOException { f(new File("d:\\"),"物件"); } }
4.執行結果圖
如圖所示,在d盤下所有檔案中共有198行含有“物件”兩字。