public class IoDemo {
public static void main(String[] args) throws IOException {BufferedReader bufr = new BufferedReader(new FileReader("d:\\java\\zz.txt"));
BufferedWriter bufw = new BufferedWriter(new FileWriter("d:\\java\\AA.txt"));
String str = null;
int count = 0;
while ((str = bufr.readLine()) != null) {
int count2 = getcount(str, "java", 0); // 7
count += count2; // 7
}
bufw.write("总个数=" + count);
bufw.flush();
bufr.close();
bufw.close();
}
public static int getcount(String str, String str2, int count) {
int len = str.indexOf("java");
count++;
return len == -1 ? count - 1 : getcount(str.substring(len + str2.length()), str2, count);
}
}
第二种方法:
import java.io.*;
import java.util.TreeMap; //简写
public class IoDemo2 {
public static void main(String[] args) throws IOException {
BufferedReader bufr = new BufferedReader(new FileReader("d:\\java\\zz.txt"));
TreeMap<Character, Integer> tp = new TreeMap<>();
int len = 0;
while ((len = bufr.read()) != -1) {
char ch = (char) len;
// if(!tp.containsKey(ch)){
// tp.put(ch,1);
// }
// else {
// tp.put(ch, tp.get(ch)+1);
// }
tp.put(ch, tp.containsKey(ch) ? tp.get(ch) + 1 : 1);
}
bufr.read();
BufferedWriter bufw = new BufferedWriter(new FileWriter("d:\\java\\zz22.txt"));
for (Character key : tp.keySet()) {
if (key == '\r') {
bufw.write("\\r" + "=" + tp.get(key));
bufw.newLine();
bufw.flush();
} else if (key == '\n') {
bufw.write("\\n" + "=" + tp.get(key));
bufw.newLine();
} else {
bufw.write(key + "=" + tp.get(key));
bufw.newLine();
bufw.flush();
}
}
bufw.close();
}
}