生成文件信息如下
---------------------------------直接贴代码--------------------------------------
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 反射
**/
public class BeanInfoUtil {
/**
* 获取对象信息 输出到文件或其他
*/
public static void setReflex() {
//这里先创一个新对象 实际工作应该是传过来的
Diary diary = new Diary();
diary.setName("邓超");
diary.setMobilefour("unbelievable");
diary.setBytxt("Amazing");
Class clazz = diary.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
RandomAccessFile raf = new RandomAccessFile("D:/123.txt", "rw");
StringBuilder sb = new StringBuilder();
System.out.println("===============>文件写入数据开始");
for (int j = 0; j < fields.length; j++) {
// 获取Bean的某个属性的描述符
PropertyDescriptor proDescriptor = new PropertyDescriptor(fields[j].getName(), Diary.class);
// 获得用于读取属性值的方法
Method methodGetUserName = proDescriptor.getReadMethod();
// 读取属性值
Object objUserName = methodGetUserName.invoke(diary);
//可以写入到文件或者读取,此处省略操作。。
System.out.println("set Method:" + objUserName.toString());
//最后一个字段不需要添加分隔符
if (j == fields.length - 1) {
sb.append(objUserName.toString());
} else {
sb.append(objUserName.toString()).append("|");
}
}
raf.write(sb.toString().getBytes("UTF-8"));
raf.close();
System.out.println("<===============文件写入数据结束");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取文件信息 输入到数据库或其他
*/
public static void getReflex() {
Diary diary = new Diary();
Class clazz = diary.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
File upFile = new File("D:/123.txt");
FileInputStream fdr = new FileInputStream(upFile);
InputStreamReader is = new InputStreamReader(fdr, "UTF-8"); //注意装载到数据库需要用GBK 到文件需要用UTF-8
BufferedReader in = new BufferedReader(is, 30 * 1024 * 1024);//50M缓存
String tmpLine = null;
String line = null;
System.out.println("===============>读取文件数据开始");
while ((tmpLine = in.readLine()) != null) {
line = tmpLine;
String data[] = line.split("\\|");
for (int j = 0; j < fields.length; j++) {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fields[j].getName(), Diary.class);
Method method = propertyDescriptor.getWriteMethod();
method.invoke(diary, data[j]);
}
//接下来可做插入数据库操作 此处省略...
System.out.println("get Method:" + diary.getName());
System.out.println("get Method:" + diary.getMobilefour());
System.out.println("get Method:" + diary.getBytxt());
System.out.println("<===============读取文件数据结束");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
setReflex();
System.out.println("\n");
getReflex();
}
}
//运行之后输出结果
===============>文件写入数据开始
set Method:邓超
set Method:unbelievable
set Method:Amazing
<===============文件写入数据结束
===============>读取文件数据开始
get Method:邓超
get Method:unbelievable
get Method:Amazing
<===============读取文件数据结束