java读取csv文件的方法,Java-读取具有各种数据类型的CSV文件的最有效方法

I'm attempting to read in a CSV file with various data types.

A row of the sheet would be like below:

Single, Monthly, Accelerated, John, Smith, 08/15/1951, Yes

I then need to assign each field to a variable name, preform some calculations, print an output and then move onto the next line in the excel sheet

Up until now, I've been using the below

ArrayList lines = new ArrayList<>();

try {

BufferedReader reader = new BufferedReader(new FileReader(fileName));

String line = null;

while ((line = reader.readLine()) != null) {

lines.add(line);

}

But this creates an array with each slot containing a long string with the text (including comma) of the corresponding excel row.

This seems inefficient and impractical as i then have to traverse each slot/string to extract the values.

Once I have the methodology, I wont have any issue writing the code but i don't know the best way to go about it

Is it better to read each cell separately and assign to a variable ?

Or is it better to read in a file once and traverse it afterwards?

Perhaps there is a more efficient way to do this task

Edit : I also though of attempting to read in the entire CSV file as a 2D array, but the different data types could be an issue..?

解决方案

You can try something similar to this. Use StringTokenizer to split the line by comma and add those elements to another List as strings in each iteration.

ArrayList> lines = new ArrayList<>();

try {

BufferedReader reader = new BufferedReader(new FileReader(fileName));

String line = null;

while ((line = reader.readLine()) != null) {

ArrayList tokens = new ArrayList<>();

StringTokenizer st = new StringTokenizer(line, ",");

while (st2.hasMoreElements()) {

tokens.add(st2.nextElement());

}

lines.add(tokens);

}

}

Now you can use proper casts to convert them to types you want. For example, to get the date,

DateFormat format = new SimpleDateFormat("mm/dd/yyyy", Locale.ENGLISH);

String dateString = lines.get(0).get(5);

Date date = format.parse(dateString);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值