Package cn.howso.deeplan.son.feeder.util;
Import Java.io.BufferedReader;
Import Java.io.BufferedWriter;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileReader;
Import Java.io.FileWriter;
Import java.io.IOException;
Import Java.util.Date;
Import Com.csvreader.CsvReader;
Import Com.csvreader.CsvWriter;
public class Readandwritecsv {
public static void Main (string[] args) throws IOException {
Date DateStart =new date ();
System.out.println (datestart+ "Hu Jintao");
String [] str = {"city_id", "City_name", "City_pid", "level"};
int [] needs = {1,2,3,4,5,6};
String instring = "";
String tmpstring = "";
File InFile = new file ("/users/shenrongrong/desktop/plan_ott_data_20180424.csv"); Read CSV file
File outfile = new file ("/users/shenrongrong/desktop/plan_ott_data_20180424_srr.csv");/output CSV
try {
BufferedReader reader = new BufferedReader (new FileReader (InFile));
BufferedWriter writer = new BufferedWriter (new FileWriter (outfile));
Csvreader CReader = new Csvreader (reader, ', ');
Csvwriter cwriter = new Csvwriter (writer, ', ');
while (Creader.readrecord ()) {
instring = Creader.getrawrecord ();//read one row of data
for (int i = 0;i < str.length;i++) {
instring = Instring.replace (Str[i], "," + str[i] + ",");
tmpstring=instring;
for (int j = 0;j < needs.length;j++) {
Tmpstring+=instring.split (",") [Needs[j]];
// }
}
The first parameter represents the array of strings to be written, each element occupies one cell, and the second argument is true to wrap after the data is finished
Cwriter.writerecord (Tmpstring.split (","), true);
Note that using the Cwriter.write (instring) method to write the data will see that the data is written only to the first cell, "," does not function to the next cell
If the Cwriter.write (String str) method is used to write the data, the Cwriter.endrecord () method is used to implement the newline
Cwriter.endrecord ()/Line Wrap
Cwriter.flush ()//Refresh Data
}
Creader.close ();
Cwriter.close ();
Date datesend =new date ();
System.out.println (datesend+ "Hu Jintao");
SYSTEM.OUT.PRINTLN ("Time Consuming:" + (Datesend.gettime ()-datestart.gettime ())/60000);
catch (FileNotFoundException ex) {
Ex.printstacktrace ();
}
}
}