Last active
December 9, 2015 22:08
-
-
Save cuixin/4334954 to your computer and use it in GitHub Desktop.
一个通过csv文件序列化到类实例的工具,因为这个跟json不太一样,是一行行的读取,中间通过tab分割,第一行实际就是类的字段定义。 通过指定一个索引文件来读取,索引文件负责设定类的名称和配置文件的路径。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Method; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
public class Csv2ObjTools { | |
private static final Logger logger = LoggerFactory.getLogger(Csv2ObjTools.class); | |
public static final boolean loadFromIndex(String filePath) { | |
FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; | |
try { | |
Object[] rects = openFile(filePath); | |
fis = (FileInputStream) rects[0]; | |
isr = (InputStreamReader) rects[1]; | |
br = (BufferedReader) rects[2]; | |
} catch (FileNotFoundException e1) { | |
logger.error("file cannot found :" + filePath); | |
} | |
try { | |
String line = null; | |
int line_no = 1; | |
while ((line = br.readLine()) != null) { | |
String[] indexes = line.split("\t"); | |
if (indexes.length != 2) { | |
logger.error(filePath + " parse error in line no: " + line_no); | |
return false; | |
} | |
String className = indexes[0]; | |
String fileNamePath = indexes[1]; | |
csv2Obj(className, fileNamePath); | |
} | |
} catch (IOException e) { | |
logger.error("", e); | |
} finally { | |
closeFile(fis, isr, br); | |
} | |
return true; | |
} | |
private static void closeFile(FileInputStream fis, InputStreamReader isr, BufferedReader br) { | |
try { | |
if (br != null) | |
br.close(); | |
} catch (IOException e) { | |
} | |
try { | |
if (isr != null) | |
isr.close(); | |
} catch (IOException e) { | |
} | |
try { | |
if (fis != null) | |
fis.close(); | |
} catch (IOException e) { | |
} | |
} | |
private static Object[] openFile(String filePath) throws FileNotFoundException { | |
File file = new File(filePath); | |
FileInputStream fis = new FileInputStream(file); | |
InputStreamReader isr = new InputStreamReader(fis); | |
BufferedReader br = new BufferedReader(isr); | |
return new Object[]{ fis, isr, br}; | |
} | |
/** | |
* 初始化实体类 | |
* @param className | |
* @return | |
* @throws Exception | |
*/ | |
private static final Object objInit(@SuppressWarnings("rawtypes") Class cls) throws Exception { | |
Object object = cls.newInstance(); | |
Method m = null; | |
try { | |
m = object.getClass().getMethod("setInstance", object.getClass()); | |
} catch (SecurityException e) { | |
} catch (NoSuchMethodException e) { | |
} | |
if (m != null) | |
m.invoke(object, object); | |
return object; | |
} | |
/** | |
* 执行解析方法(doParse) | |
* @param object | |
* @throws Exception | |
*/ | |
private static final void objDoParse(Object object) throws Exception { | |
Method mparse = null; | |
try { | |
mparse = object.getClass().getMethod("doParse"); | |
} catch (SecurityException e) { | |
} catch (NoSuchMethodException e) { | |
} | |
if (mparse != null) | |
mparse.invoke(object); | |
} | |
private static final boolean csv2Obj(String className, String filePath) { | |
FileInputStream fis = null; InputStreamReader isr = null; BufferedReader br = null; | |
try { | |
Object[] rects = openFile(AppSettings.getFilePath() + filePath); | |
fis = (FileInputStream) rects[0]; | |
isr = (InputStreamReader) rects[1]; | |
br = (BufferedReader) rects[2]; | |
} catch (FileNotFoundException e1) { | |
logger.error("file cannot found :" + filePath); | |
} | |
try { | |
String line = null; | |
int line_no = 1; | |
String fieldline = br.readLine(); | |
if (fieldline == null || fieldline.length() == 0) { | |
logger.error(className + ":" + filePath + "'s fieldline is null"); | |
return false; | |
} | |
@SuppressWarnings("rawtypes") | |
Class cls = Class.forName(className); | |
Field[] fields = getAllFields(fieldline, cls); | |
logger.debug("begin to init " + className); | |
while ((line = br.readLine()) != null) { | |
Object object = objInit(cls); | |
String[] fieldValueStrings = line.split("\t"); | |
lineToData(object, fields, fieldValueStrings, line_no++); | |
pushData(object); | |
logger.debug("\t" + className + " push data ..."); | |
objDoParse(object); | |
} | |
logger.debug("end to init " + className); | |
} catch (Exception e) { | |
logger.error("", e); | |
return false; | |
} finally { | |
closeFile(fis, isr, br); | |
} | |
return true; | |
} | |
private static final Field[] getAllFields(String line, @SuppressWarnings("rawtypes") Class cls) throws SecurityException, NoSuchFieldException { | |
String[] strings = line.split("\t"); | |
Field[] fields = new Field[strings.length]; | |
int i = 0; | |
for (String fieldstr:strings) { | |
Field field = cls.getDeclaredField(fieldstr); | |
fields[i++] = field; | |
} | |
return fields; | |
} | |
private static final void lineToData(Object object, Field[] fields, String fieldValueStrings[], int lineNo) throws Exception { | |
if (fields.length != fieldValueStrings.length) { | |
throw new Exception("line " + lineNo + " length not equals"); | |
} | |
int i = 0; | |
for (; i < fields.length; i++) { | |
Field field = fields[i]; | |
String fieldValueString = fieldValueStrings[i]; | |
field.setAccessible(true); | |
if (field.getType() == String.class) { | |
field.set(object, fieldValueString); | |
} else if (field.getType().getName().equals("float")) { | |
field.setFloat(object, Float.parseFloat(fieldValueString)); | |
} else if (field.getType().getName().equals("double")) { | |
field.setDouble(object, Double.parseDouble(fieldValueString)); | |
} else if (field.getType().getName().equals("int")) { | |
field.setInt(object, Integer.parseInt(fieldValueString)); | |
} else if (field.getType().getName().equals("boolean")) { | |
field.setBoolean(object, Boolean.parseBoolean(fieldValueString)); | |
} else if (field.getType().getName().equals("byte")) { | |
field.setByte(object, Byte.parseByte(fieldValueString)); | |
} else if (field.getType().getName().equals("short")) { | |
field.setShort(object, Short.parseShort(fieldValueString)); | |
} else if (field.getType().getName().equals("long")) { | |
field.setLong(object, Long.parseLong(fieldValueString)); | |
} | |
field.setAccessible(false); | |
} | |
} | |
private static final boolean pushData(Object object) { | |
Method m = null; | |
try { | |
m = object.getClass().getMethod("pushData", object.getClass()); | |
} catch (SecurityException e) { | |
} catch (NoSuchMethodException e) { | |
} | |
if (m != null) { | |
try { | |
m.invoke(object, object); | |
} catch (Exception e) { | |
logger.error("{} in {}", object, e); | |
return false; | |
} | |
return true; | |
} else | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment