查看文件中每行出现的次数--小程序
1 package com.test;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.Iterator;
9 import java.util.LinkedHashMap;
10 import java.util.List;
11 import java.util.Map;
12
13 public class FileReadTest {
14 private static BufferedReader br;
15
16 public static void main(String[] args) throws IOException {
17 File file = new File("E:/1.txt");
18 if (!file.exists() || file.isDirectory()) {
19 System.out.println("文件不存在");
20 }
21 br = new BufferedReader(new FileReader(file));
22 List<String> list = new ArrayList<String>();
23 String readLine = "";
24 while((readLine = br.readLine()) != null){
25 if(!"".equals(readLine.trim())){
26 list.add(readLine.trim());
27 }
28 }
29 Map<String,Integer> result = new LinkedHashMap<String,Integer>();
30 for(String str : list){
31 if(!result.keySet().contains(str)){
32 result.put(str, 1);
33 }else{
34 result.put(str, result.get(str)+1);
35 }
36 }
37
38 Iterator iter = result.keySet().iterator();
39 while(iter.hasNext()){
40 String key = (String)iter.next();
41 System.out.println(key + "出现的次数为:" + result.get(key));
42 }
43
44
45 }
46 }
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.Iterator;
9 import java.util.LinkedHashMap;
10 import java.util.List;
11 import java.util.Map;
12
13 public class FileReadTest {
14 private static BufferedReader br;
15
16 public static void main(String[] args) throws IOException {
17 File file = new File("E:/1.txt");
18 if (!file.exists() || file.isDirectory()) {
19 System.out.println("文件不存在");
20 }
21 br = new BufferedReader(new FileReader(file));
22 List<String> list = new ArrayList<String>();
23 String readLine = "";
24 while((readLine = br.readLine()) != null){
25 if(!"".equals(readLine.trim())){
26 list.add(readLine.trim());
27 }
28 }
29 Map<String,Integer> result = new LinkedHashMap<String,Integer>();
30 for(String str : list){
31 if(!result.keySet().contains(str)){
32 result.put(str, 1);
33 }else{
34 result.put(str, result.get(str)+1);
35 }
36 }
37
38 Iterator iter = result.keySet().iterator();
39 while(iter.hasNext()){
40 String key = (String)iter.next();
41 System.out.println(key + "出现的次数为:" + result.get(key));
42 }
43
44
45 }
46 }