Java I/O流实现txt内固定字符查找统计
在文本文件bigbook.txt中包含有很长篇幅的英文短文,编写程序要求统计文件所有的短文中包含英文字母”A”的个数,并显示统计的时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| package com.practice; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import org.xml.sax.InputSource;
public class Static { public static void main(String[] args) { try { long time = System.currentTimeMillis(); String path = "V:/java练习/bigbook.txt"; File file = new File(path); if (!file.exists()) { file.createNewFile(); } InputStream in = new FileInputStream(file); int len, sum = 0; while ((len = in.read()) != -1) { if (len == 'A') { sum++; } } in.close(); time = System.currentTimeMillis() - time; System.out.println("文中'a'的个数是:" + sum); System.out.println("查找所用时间是:" + time + "微秒"); } catch (Exception e) { e.printStackTrace(); } } }
|