可編譯為jar檔,重複使用
Source code:
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.regex.Matcher; public class FindKeyWord { public static void main(String args[]) throws IOException{ ReadClass mReadClass = new ReadClass(); mReadClass.readData(); } } class ReadClass{ int count = 0; public void readData(){ //String dirPath = "C:\\Users\\Test\\Desktop\\"; String dirPathTemp = System.getProperty("user.dir"); String dirPath = Matcher.quoteReplacement(dirPathTemp); CharSequence findWord = "keyword"; File dir = new File(dirPath); StringBuilder sb = new StringBuilder(); if(dir.exists() && dir.isDirectory()){ String[] names = dir.list(); for(String name: names){ FileReader fr; try { fr = new FileReader(dirPath + "\\" + name); BufferedReader bf = new BufferedReader(fr); String data = null; try { while((data = bf.readLine()) != null){ if(data.contains(findWord)){ String regString = "="; String[] StringArray = data.split(regString); output(StringArray[1], dirPath); } } } catch (IOException e) { e.printStackTrace(); } try { bf.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }else{ String info = "路徑錯誤: " + dirPath + "請重新輸入"; } } public void output(String str, String dirPath) throws IOException{ String filePath = dirPath + "\\" + "data.txt"; FileWriter mFileWriter = new FileWriter(filePath, true); String item = null; if((count/10) < 1){ item = " " + Integer.toString(count); }else if((count/10) < 10){ item = " " + Integer.toString(count); }else{ item = Integer.toString(count); } String mString = new String(item + ", keyword = " + str + "\r\n"); mFileWriter.write(mString); mFileWriter.flush(); mFileWriter.close(); count++; } }
沒有留言:
張貼留言