`
Xcupidtx
  • 浏览: 14943 次
社区版块
存档分类
最新评论

从文件中查出字符串”mobnet”出现的次数

    博客分类:
  • JAVA
阅读更多
package com.ebiz.tsu.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test {
	static String subStr = "mobnet1";
	static int count = 0;
	
	public static void main(String[] args) {
		write(subStr, 10, false);
		String str = read(new File("E://test.txt")).toString();
		findSubString(str ,"mobnet", 0);
		System.out.println(count);
	}

	/**
	 * 递归方法,查看某个subStr出现过几次
	 * @param str
	 * @param subStr
	 * @param i 从第几个字符开始查找
	 * @return
	 */
	private static int findSubString(String str, String subStr, int i) {
		int index = str.indexOf(subStr, i);
		if (-1 != index) {
			i = index + subStr.length();
			count ++;
			findSubString(str, subStr, i);
		}
		return count;
	}

	/**
	 * 读文件内容到StringBuffer
	 * @param file
	 * @return
	 */
	private static StringBuffer read(File file) {
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));  
			String data = null;
			while((data = br.readLine())!=null)  
			{  
				sb.append(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("读取文件成功");
		System.out.println("文件内容为");
		System.out.println(sb);
		return sb;
	}

	/**
	 * 将某个字符串重复的写入文件
	 * @param str 字符串
	 * @param count 重复次数
	 * @param append 写入方式,true 在原文件末尾增加, false 覆盖原文件
	 */
	private static void write(String str, int count, boolean append ) {
		try {
			OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(new File("E://test.txt"), append));
			for (int i=0; i<count; i++) {
				osw.write(str, 0, str.length());
			}
			osw.flush();
			System.out.println("写入文件成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics