-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadFile.java
More file actions
51 lines (44 loc) · 1.99 KB
/
Copy pathReadFile.java
File metadata and controls
51 lines (44 loc) · 1.99 KB
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
package heyingzhe;
import java.util.*;
import java.io.*;
public class ReadFile {
// 从filepath中读取txt文件,并按照分隔符进行读取文件,保存存list数据类型
public static List<Map<String, String>> readFile(String filePath, String delimiter) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filePath)); //读取文件
List<Map<String, String>> records = new ArrayList<>(); //创建arraylist数据,里面储存map型数据
String line;
// 读取标题行,作为字段名
String[] fieldNames = reader.readLine().split(delimiter);
// 逐行读取数据
while ((line = reader.readLine()) != null) {
String[] fields = line.split(delimiter);
Map<String, String> record = new HashMap<>();
for (int i = 0; i < fieldNames.length; i++) {
record.put(fieldNames[i].trim(), fields[i].trim());
}
records.add(record);
}
reader.close();
return records;
}
// 读取数据
public static List<Map<String, String>> readFile(String filePath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filePath)); //读取文件
List<Map<String, String>> records = new ArrayList<>(); //创建arraylist数据,里面储存map型数据
String line;
String delimiter = "\\s+";
// 读取标题行,作为字段名
String[] fieldNames = reader.readLine().split(delimiter);
// 逐行读取数据
while ((line = reader.readLine()) != null) {
String[] fields = line.split(delimiter);
Map<String, String> record = new HashMap<>();
for (int i = 0; i < fieldNames.length; i++) {
record.put(fieldNames[i].trim(), fields[i].trim());
}
records.add(record);
}
reader.close();
return records;
}
}