
实体com.google.code.gson gson 2.8.6
@Data
public class Student {
private Integer no;
private String name;
private String sex;
private Double score;
}
测试
TextUtil在这 TextUtil工具类
@Test
public void testRead() {
Gson gson = new Gson();
String path = "D:\Student.txt";
List list = new ArrayList<>();
try {
TextUtil.read(path,(String line) ->{
list.add(line);
});
} catch (IOException e) {
e.printStackTrace();
}
List students = new ArrayList<>();
for (int i = 1; i < list.size(); i++) {
String s = list.get(i);
//去除文本中空格
String s1 = s.replaceAll(" ", "");
String[] strings = s1.split(",");
Student student = new Student();
student.setNo(Integer.valueOf(strings[0]));
student.setName(strings[1]);
student.setSex(strings[2]);
student.setScore(Double.valueOf(strings[3]));
students.add(student);
}
String json = gson.toJson(students);
System.out.println("json = " + json);
}
Student.txt