统计一个字符串在文本文件中的出现次数

代码实现:

package com.jn.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

public class StringTimes {
	 public static int getKeyStringCount(String str, String key) {          
         int count = 0;  
         int index = 0;             
         while((index = str.indexOf(key,index))!=-1){                 
             index = index + key.length();  
             count++;                 
         }              
         return count;  
     }  
    
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File file = new File("D:/设计模式.txt");
		FileInputStream fis = null;
		try{
			fis = new FileInputStream(file);
			int len = 0;
			byte[] buf = new byte[1024];
			String str = null;
			while((len = fis.read(buf)) !=-1){
				str = new String(buf, 0, len,"GBK");			
			}
			Scanner sc  = new Scanner(System.in);
			System.out.println("请输入你要查询字符串:");
			 String key = sc.nextLine();  
             int count = getKeyStringCount(str,key);  
             System.out.println("文件中此字符串出现次数为:"+count+"次");  
		}catch(FileNotFoundException e){
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

  运行及结果:

请输入你要查询字符串:
设计模式
文件中此字符串出现次数为:10次

  

posted @ 2017-11-09 20:46  ·卿欢·  阅读(3124)  评论(0编辑  收藏  举报