IO-字符流 练习
LineNumberReader是BufferedReader的子类, 具有相同的功能, 并且可以统计行号 * 调用getLineNumber()方法可以获取当前行号 * 调用setLineNumber()方法可以设置当前行号 * LineNumberReader lnr = new LineNumberReader(new FileReader("aaa.txt")); String line; lnr.setLineNumber(100); //设置行号 默认是从0行开始 while((line = lnr.readLine()) != null) { System.out.println(lnr.getLineNumber() + ":" + line);//获取行号 } lnr.close();
public class test2 { /* * 获取一个文本上每个字符出现的次数,将结果写在times.txt上 */ public static void main(String[] args) throws IOException { BufferedReader b1 = new BufferedReader(new FileReader("zzz.txt")); TreeMap<Character, Integer> t1 = new TreeMap<>(); int ch ; while((ch = b1.read()) != -1){ char c = (char)ch; //向下强转 if (!t1.containsKey(c)) { t1.put(c, 1); }else{ t1.put(c, t1.get(c)+1); } // 可以用三元运算符写 } b1.close(); BufferedWriter b2 = new BufferedWriter(new FileWriter("time.txt")); for (Character key : t1.keySet()) { switch (key) { case '\t': b2.write("\\t" + "=" + t1.get(key)); break; case '\n': b2.write("\\n" + "=" + t1.get(key)); break; case '\r': b2.write("\\r" + "=" + t1.get(key)); break; default: b2.write(key + "=" + t1.get(key)); break; } //b2.write(key + "=" + t1.get(key)); //写出键和值 b2.newLine(); } b2.close(); } }
竹杖芒鞋轻胜马,一蓑烟雨任平生。
回首向来萧瑟处,也无风雨也无晴。