利用java语言统计一个txt文件中的字符个数,以及替换你指定的相关字符并输出。
统计字符
以空格为分隔符来区分字符(可以利用其他的标志为分隔符),遍历该文件,统计字符以及他们的个数输出。
package jr;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Test3 {
public static void main(String[] args) {
//1,读文件
BufferedReader br = null;
try {
Map<String,Integer> map = new HashMap<String,Integer>();
br = new BufferedReader(new FileReader("d:/mywords.txt"));
String line;
while(null != (line = br.readLine())){
// System.out.println(line);
String[] ss = line.split("\\s+");//+量词 {1,} *{0,} ?{0,1} 正则表达式
for(String s : ss){
if(map.containsKey(s)){
map.put(s, map.get(s)+1);
}else{
map.put(s, 1);
}
}
}
Set<String> keys = map.keySet();
for(String key : keys){
System.out.println(key + "有:" + map.get(key) + "个.");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(null != br){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
参考截图:
修改其中指定字符并替换
package jr;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Updatetemplate {
public static void main(String[] args) throws IOException {
char [] c = new char[500];
FileReader fr = new FileReader("D:\\template.txt");
int num = fr.read(c);
String str = new String(c,0,num);
//System.out.println(str);
fr.close();
System.out.println("=========输入姓名==============");
Scanner sc = new Scanner(System.in);
System.out.print("请输入人的名字:");
String ss = sc.next();
String str1;
str1 = str.replaceAll("name", ss);
System.out.print("请输入狗的名字:");
String st = sc.next();
str1 = str1.replaceAll("dog",st);
System.out.println(str1);
FileWriter fw = new FileWriter("D:\\"+ss+".txt");
fw.write(str1);
fw.close();
}
}
参考截图:
以上就是这篇的内容,若有什么疑惑或者您发现错误的地方,请您指出。谢谢!