Fork me on GitHub

java读取txt文件

源码:

mark

mark

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.util.HashMap;

import java.util.Map;

public class TXTParseUtils {

private static final Integer ONE = 1;

public static void main(String[] args) {

Map<String, Integer> map = new HashMap<String, Integer>();

/* 读取数据 */

try {

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("111.txt")),

"UTF-8"));

String lineTxt = null;

while ((lineTxt = br.readLine()) != null) {

String[] names = lineTxt.split(",");

for (String name : names) {

if (map.keySet().contains(name)) {

map.put(name, (map.get(name) + ONE));

} else {

map.put(name, ONE);

}

}

}

br.close();

} catch (Exception e) {

System.err.println("read errors :" + e);

}

/* 输出数据 */

try {

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("final.txt")),

"UTF-8"));

for (String name : map.keySet()) {

bw.write(name + " " + map.get(name));

bw.newLine();

}

bw.close();

} catch (Exception e) {

System.err.println("write errors :" + e);

}

}

}

测试数据:

文苏洋,闫少翀,孟超
张育铭,王洪展
程浩男,路佳琦
罗天实,wsy,ysc,mc,zym
whz,ljq,lts
chn

运行结果:

闫少翀 1
罗天实 1
ysc 1
whz 1
chn 1
王洪展 1
lts 1
孟超 1
文苏洋 1
张育铭 1
程浩男 1
zym 1
ljq 1
mc 1
路佳琦 1
wsy 1

-------------本文结束感谢您的阅读-------------
undefined