【笔记】Txt文件解析工具类
1.TxtUtils
package com.sisyphus.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class TxtUtils {
public static List<List<String>> txtToList(String filePath, String separator, Boolean isEndSeparatorExist, Integer start, Integer end){
ArrayList<List<String>> lists = new ArrayList<>();
try {
File file = new File(filePath);
if (file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
for(int i = 0; i < start; i++){
br.readLine();
}
String lineTxt;
while ((lineTxt = br.readLine()) != null) {
List<String> list = new ArrayList<>();
int left = 0;
int right = 0;
int sepLen = separator.length();
int lineLen = lineTxt.length();
int currentIndex = 0;
while(right < lineLen && currentIndex+sepLen != lineLen){
while(right < lineLen && lineTxt.charAt(right) != separator.charAt(0)){
right++;
}
if(right == lineLen) break;
String temp = lineTxt.substring(left,right);
list.add(temp);
left = right + sepLen;
currentIndex = right;
right = left;
}
if(!isEndSeparatorExist){
list.add(lineTxt.substring(left, lineLen));
}
lists.add(list);
}
br.close();
} else {
System.out.println("文件不存在!");
}
} catch (Exception e) {
e.printStackTrace();
}
for(int i = 0; i < end; i++){
lists.remove(lists.size()-1);
}
return lists;
}
public static <T> List<T> listToDTO(Class<T> dto, List<List<String>> stringLists){
List<T> dtoList = new ArrayList<>();
try {
for (List<String> stringList : stringLists) {
T newInstance = dto.newInstance();
Class<?> clazz = newInstance.getClass();
Field[] fields = clazz.getDeclaredFields();
int j = 0;
for (Field field : fields) {
field.setAccessible(true);
String fieldName = field.getName();
String initial = fieldName.substring(0, 1);
String replace = fieldName.replaceFirst(initial, initial.toUpperCase());
Class<?> type = field.getType();
Method method = newInstance.getClass().getMethod("set" + replace, type);
method.invoke(newInstance, stringList.get(j));
j++;
}
dtoList.add(newInstance);
}
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return dtoList;
}
public static <T> List<T> txtToDTO(Class<T> dto, String filePath, String separator, Boolean isEndSeparatorExist, Integer start, Integer end){
return listToDTO(dto, txtToList(filePath, separator, isEndSeparatorExist, start, end));
}
}