java读取文件中每一行字符串的出现次数
读取文件中每一行字符串的出现次数,因为有了百度,就懒得想,看到别人写的,才恍然大悟:
用map存储数据呀,key值肯定是不重复的,可以把每一行字符串存入key值,而value存放本条字符串的出现次数;
按理说这么简单的问题我应该第一时间想到的,但是懒呀。。。。
花不多说,上代码:
public static void main(String[] args) { // 文件中每一行字符串出现的次数 HashMap<String, Integer> stringMap = new HashMap<>(); BufferedReader br = null; try { br = new BufferedReader(new FileReader("C:\\Users\\YET-SH28\\Desktop\\setkey.txt")); String readLine = null; while ((readLine = br.readLine()) != null) { int count = 0; if (stringMap.containsKey(readLine)) { count = stringMap.get(readLine); } stringMap.put(readLine, count + 1); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } }
参考链接:https://blog.csdn.net/zhaodecang/article/details/78244976