文件内容、关键字匹配,split 和 indexOf 均可实现
生活随笔
收集整理的這篇文章主要介紹了
文件内容、关键字匹配,split 和 indexOf 均可实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
package test;import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List;public class KeyWordMatch {public static void main(String[] args) {String path = "C:\\Users\\JiangLi\\Desktop\\DBConnection.java"; //文件路徑List<String> keyWords = new ArrayList<String>(); //關鍵字mapkeyWords.add("String");keyWords.add("public");keyWords.add("void");keyWords.add("new");keyWords.add("try");keyWords.add("static");keyWords.add("import");try {match(path,keyWords); match2(path,keyWords);} catch (Exception e) {e.printStackTrace();}}/*** 運用split方法確定關鍵字個數* @param path* @param keyWords* @throws Exception */private static void match2(String path, List<String> keyWords) throws Exception {File file = new File(path);if(file.exists()){FileInputStream fis = new FileInputStream(file);InputStreamReader isr = new InputStreamReader(fis,"utf-8");BufferedReader br = new BufferedReader(isr);StringBuffer sb = new StringBuffer();String data = null;while((data=br.readLine())!=null){sb.append(data+"\n");}//System.out.println("Java文件內容如下:");//System.out.println(sb.toString());System.out.println("各關鍵字出現次數如下:");for(String keyword:keyWords){String content = sb.toString();String[] strs = content.split(keyword);System.out.println("出現關鍵字"+keyword+"的個數為:"+(strs.length-1));}}else{System.out.println("文件不存在!");}}private static void match(String path, List<String> keyWords) throws Exception {File file = new File(path);if(file.exists()){FileInputStream fis = new FileInputStream(file);InputStreamReader isr = new InputStreamReader(fis,"utf-8");BufferedReader br = new BufferedReader(isr);StringBuffer sb = new StringBuffer();String data = null;while((data=br.readLine())!=null){sb.append(data+"\n");}//System.out.println("Java文件內容如下:");//System.out.println(sb.toString());System.out.println("各關鍵字出現次數如下:");for(String keyword:keyWords){int count=0;boolean boo = true;String content = sb.toString();while(boo){int index = content.indexOf(keyword);if(index == -1){boo = false;}else{count++;content = content.substring(index+keyword.length());}}System.out.println("出現關鍵字"+keyword+"的個數為:"+count);}}else{System.out.println("文件不存在!");}} }轉載于:https://my.oschina.net/jiangli0502/blog/142157
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的文件内容、关键字匹配,split 和 indexOf 均可实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 歪枣网后台设计
- 下一篇: 关于tolua的使用