我想写一个可以打印和修改不规则csv文件的程序。格式如下:
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 ..........
例如,数据可以如下所示:
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
我是一个初学者,但是我没有在网上找到任何可行的资源来解决此类问题。我主要关心的是,我们如何遍历循环并确定俱乐部的日期和名称,并将其输入数组?请指教。
我认为这应该对您有所帮助。基本上,您的CSV杂乱无章。下面是我安排您的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(); }
这是您将为此获得的输出
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),
我正在从csv.txt中读取文件。while循环遍历文本文件的每一行。所有字段都存储在变量中。下一个日期到来时,我将它们全部写入输出文件。在while循环终止后,csv的最后一行被写入文件。