java csv 修改一行,在Java中修改复杂的CSV文件

I wanted to write a program which can print, and modify the irregular csv files. The format is as follows:

1.date

2.organization name

3. student name, id number, residence

student name, id number, residence

student name, id number, residence

student name, id number, residence

student name, id number, residence

1.another date

2.another organization name

3. student name, id number, residence

student name, id number, residence

student name, id number, residence

..........

For instance, the data may be given as follows:

1. 10/09/2016

2. cycling club

3. sam, 1000, oklahoma

henry, 1001, california

bill, 1002, NY

1. 11/15/2016

2. swimming club

3. jane, 9001, georgia

elizabeth, 9002, lousiana

I am a beginner and I have not found any viable resource online which deals with this type of problem. My main concern is, how do we iterate through the loop and identify the date and name of the club, and feed them into a array?

Please advise.

解决方案

I think this should be helpful for you. Basically there should be some pattern in your messed up csv. Below is my code to arrange your csv

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {

PrintWriter writer = new PrintWriter("file.txt", "UTF-8");

try{

//Create object of FileReader

FileReader inputFile = new FileReader("csv.txt");

//Instantiate the BufferedReader Class

BufferedReader bufferReader = new BufferedReader(inputFile);

//Variable to hold the one line data

String line;

String date="";String org ="";String student ="";

// Read file line by line and print on the console

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

if(line.contains("1.")){

if(date!="" || org!=""){

writer.println(date+","+org+","+student);

student ="";

}

date = line.substring(2);

}else if(line.contains("2.")){

org = line.substring(2);

}else{

line = "("+line+")";

student += line+",";

}

System.out.println(line);

}

writer.println(date+","+org+","+student);

//Close the buffer reader

bufferReader.close();

}catch(Exception e){

System.out.println("Error while reading file line by line:" + e.getMessage());

}

writer.close();

}

This is the output you will get for this

10/09/2016, cycling club,(3. sam, 1000, oklahoma),( henry, 1001, california),( bill, 1002, NY),

11/15/2016, swimming club,(3. jane, 9001, georgia),( elizabeth, 9002, lousiana),

I am reading the file from csv.txt. while loop goes through each line of text file.all the fields are stored in a variable. When next date comes I write all of them into output file. Last line of the csv is written to file after the while loop terminates.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值