读取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
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。