这是我现有的csv文件:
userid,name
1,Jim
2,Sally
3,Bob
我可以使用CsvMapReader / Writer添加另一列,使其看起来像:
userid,name,time
1,Jim,64913824823208
2,Sally,64913824900056
3,Bob,64913824966956
但是,如果我想添加另一列以使我的csv看起来像:
userid,name,time,day
1,Jim,64913824823208,Mon
2,Sally,64913824900056,Mon
3,Bob,64913824966956,Mon
我如何实现这一目标?
我用来添加列的代码段是:
CsvPreference prefs = CsvPreference.STANDARD_PREFERENCE;
mapReader = new CsvMapReader(new FileReader(path+csvFileName), prefs);
mapWriter = new CsvMapWriter(new FileWriter(path+desiredFileNameWithDateOfPull), prefs);
// header used to read the original file
final String[] readHeader = mapReader.getHeader(true);
// header used to write the new file
// (same as 'readHeader', but with additional column)
final String[] writeHeader = new String[readHeader.length + 1];
System.arraycopy(readHeader, 0, writeHeader, 0, readHeader.length);
final String str= "day";
writeHeader[writeHeader.length - 1] = str;
mapWriter.writeHeader(writeHeader);
Map<String, String> row;
while( (row = mapReader.read(readHeader)) != null ) {
// add your column with desired value
row.put(str, "Mon");
mapWriter.write(row, writeHeader);
}
答案 0 :(得分:0)
public static void main(String[] args) 抛出 IOException {
ICsvMapReader mapReader = null;
ICsvMapWriter mapWriter = null;
try {
CsvPreference prefs = CsvPreference.STANDARD_PREFERENCE;
mapReader = new CsvMapReader(new FileReader("input.csv"), prefs);
mapWriter = new CsvMapWriter(new FileWriter("output.csv"), prefs);
// header used to read the original file
final String[] readHeader = mapReader.getHeader(true);
// header used to write the new file
// (same as 'readHeader', but with additional column)
final String[] writeHeader = new String[readHeader.length + 2];
System.arraycopy(readHeader, 0, writeHeader, 0, readHeader.length);
final String timeHeader = "time";
final String str="day";
writeHeader[writeHeader.length - 2] = timeHeader;
writeHeader[writeHeader.length-1]= str;
mapWriter.writeHeader(writeHeader);
Map<String, String> row;
while( (row = mapReader.read(readHeader)) != null ) {
// add your column with desired value
row.put(timeHeader, String.valueOf(System.nanoTime()));
row.put(str,"mon");
mapWriter.write(row, writeHeader);
}
}
finally {
if( mapReader != null ) {
mapReader.close();
}
if( mapWriter != null ) {
mapWriter.close();
}
}