public class Test {
// 统计数字或者字符出现的次数
public static TreeMap Pross(String str) {
char[] charArray = str.toCharArray();
TreeMap tm = new TreeMap();
for (int x = 0; x < charArray.length; x++) {
if (!tm.containsKey(charArray[x])) {
tm.put(charArray[x], 1);
} else {
int count = tm.get(charArray[x]) + 1;
tm.put(charArray[x], count);
}
}
return tm;
}
public static void main(String[] args) {
BufferedReader br = null;
int line = 0;
String str = "";
StringBuffer sb = new StringBuffer();
try {
br = new BufferedReader(new FileReader("c:\\1.txt"));
while ((str = br.readLine()) != null) {
sb.append(str);
++line;
}
System.out.println("\n文件行数: " + line);
System.out.println("\n文件内容: " + sb.toString());
TreeMap tm = Pross(sb.toString());
System.out.println("\n字符统计结果为:" + tm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
-
public static int count(String filename, String target)
-
throws FileNotFoundException, IOException {
-
FileReader fr = new FileReader(filename);
-
BufferedReader br = new BufferedReader(fr);
-
StringBuilder strb = new StringBuilder();
-
while (true) {
-
String line = br.readLine();
-
if (line == null) {
-
break;
-
}
-
strb.append(line);
-
}
-
String result = strb.toString();
-
int count = 0;
-
int index = 0;
-
while (true) {
-
index = result.indexOf(target, index + 1);
-
if (index > 0) {
-
count++;
-
} else {
-
break;
-
}
-
}
-
br.close();
-
return count;
-
}
-
-
public static void main(String[] args) {
-
try {
-
System.out.println(count("D:\\zuidaima.txt", "a"));
-
} catch (FileNotFoundException e) {
-
e.printStackTrace();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
加载中,请稍候......