读取csv文件并封装数据为对象

例如
图中的一个 .csv 文件,需要读取数据封装对象进行数据持久化。
public static void readcsv(string readpath, arraylist list)
{
file infile = new file(readpath);
try
{
bufferedreader reader = new bufferedreader(new filereader(infile));
boolean sign = false; //用来跳过第一行的名称
while(reader.ready())
{
string line = reader.readline();
stringtokenizer st = new stringtokenizer(line, ",");
int date, time, num_transaction, response_time;
double sucrate;
if (st.hasmoretokens() && sign)
{
date = integer.valueof(st.nexttoken().trim());
time = integer.valueof(st.nexttoken().trim());
num_transaction = integer.valueof(st.nexttoken().trim());
sucrate = double.valueof(st.nexttoken().trim());
response_time = integer.valueof(st.nexttoken().trim());
sample sample = new sample(date, time, num_transaction, sucrate, response_time);
list.add(sample);
}
else
{
sign = true;
}
}
reader.close();
}
catch (filenotfoundexception e)
{
e.printstacktrace();
}
catch (ioexception e)
{
e.printstacktrace();
}
}当有多个对象时
可以传入一个 class对象来获取到需要封装对象的类名,进一步实现方法一般化:
public class readcsv {
public static void readcsv(inputstream inputstream, arraylist<object> list, class cls){
bufferedreader reader = null;
try {
reader = new bufferedreader(new inputstreamreader(inputstream));
boolean flag = false;
arraylist<string> headerlist = new arraylist();
while(reader.ready()){
string line = reader.readline();
stringtokenizer st = new stringtokenizer(line,",");
//处理当前行数据
if(st.hasmoretokens() && flag){
string typename = cls.getsimplename();
//如果文件中存储的是 energyprovince类信息
if(typename.equals("energyprovice")){
string provincename = st.nexttoken();
// float year2019 = float.valueof(st.nexttoken());
// float year2018 = float.valueof(st.nexttoken());
float year2017 = float.valueof(st.nexttoken());
float year2016 = float.valueof(st.nexttoken());
float year2015 = float.valueof(st.nexttoken());
float year2014 = float.valueof(st.nexttoken());
float year2013 = float.valueof(st.nexttoken());
float year2012 = float.valueof(st.nexttoken());
float year2011 = float.valueof(st.nexttoken());
map<string,float> datamap = new hashmap();
// datamap.put(headerlist.get(1),year2019);
// datamap.put(headerlist.get(2),year2018);
datamap.put(headerlist.get(1),year2017);
datamap.put(headerlist.get(2),year2016);
datamap.put(headerlist.get(3),year2015);
datamap.put(headerlist.get(4),year2014);
datamap.put(headerlist.get(5),year2013);
datamap.put(headerlist.get(6),year2012);
datamap.put(headerlist.get(7),year2011);
list.add(new energyprovice(provincename,datamap));
}
}
else{ //添加表头到 list 集合
while(st.hasmoretokens()){
headerlist.add(st.nexttoken());
}
flag=true;
}
}
} catch (exception e) {
e.printstacktrace();
} finally {
if(reader!=null)
try {
reader.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论