最近在做一个读取文本的小工具,编码重复性的工作。该工具是读取文本文件指定的行,并且指定的第一行作为Map的key,其他行为value。如下图,读取第1到4行,会生成一个List<Map>,每个Map中是{"goods": "123"}
。读取第5到7行,生成[{"name":"拉拉", "phone":"13570885458", "parentphone":"10086"}, {}]
。
package me.zebin.demo.javaio;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.*;
import java.util.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class JavaioApplicationTests {
@Test
public void contextLoads() throws Exception {
List<Map> goodsList = readText2Map("C:\\Users\\huang\\Desktop\\io.txt", 1, 4);
List<Map> agentList = readText2Map("C:\\Users\\huang\\Desktop\\io.txt", 5, 7);
}
public List<Map> readText2Map(String filePath, int startLine, int endLine) {
List<Map> resultList = new ArrayList<>();
// 存放标头
List<String> headerList = null;
try {
// 文件读取准备
InputStream is = new FileInputStream(filePath);
Reader r = new InputStreamReader(is, "gb2312");
BufferedReader br = new BufferedReader(r);
// 读取行
for (int i = 1; i <= endLine; i++) {
String line = br.readLine();
if (i < startLine) {
continue;
}
// 处理行
line = line.trim();
List<String> elementList = Arrays.asList(line.split(" "));
// 标头
if(i == startLine){
headerList = elementList;
continue;
}
Map<String, String> m = new HashMap<>();
for(int j = 0; j < headerList.size(); j++){
m.put(headerList.get(j), elementList.get(j));
}
resultList.add(m);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
}
网友评论