SuperCSV附加而不是覆盖?

时间:2013-03-31 13:42:01

标签: java android csv supercsv

是否可以在CSV文件中添加新行,而不是覆盖最后一行?

这是我想要添加新行时调用的方法:

private static void writeWithCsvMapWriter() throws Exception 
{
    final String[] header = new String[] { "Engineer", "Time/Date", "Project", "Test ID", "Data Centre", "Data Hall", "Row", "Grille", "I/S" };

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd_HH:mm:ss");
    String currentDateandTime = sdf.format(new Date());

    final Map<String, Object> NewRow = new HashMap<String, Object>();
    NewRow.put(header[0], Name.getText().toString());
    NewRow.put(header[1], currentDateandTime);
    NewRow.put(header[2], "Expect");
    NewRow.put(header[3], TestID.getText());
    NewRow.put(header[4], DataCentre.getText());
    NewRow.put(header[5], DataHall.getText());
    NewRow.put(header[6], Row.getText());
    NewRow.put(header[7], Grille.getText());
    NewRow.put(header[8], IS.getText());

    ICsvMapWriter mapWriter = null;

    try 
    {
        mapWriter = new CsvMapWriter(new FileWriter("data/data/" + PACKAGE_NAME +"/writeWithCsvMapWriter.csv"), CsvPreference.STANDARD_PREFERENCE);

        final CellProcessor[] processors = getProcessors();

        mapWriter.writeHeader(header);
        mapWriter.write(NewRow, header, processors);  
    }
    finally 
    {
        if( mapWriter != null ) 
        {
            mapWriter.close();
        }
    }
}

由于

2 个答案:

答案 0 :(得分:4)

true添加到new FileWriter中的参数:

mapWriter = new CsvMapWriter(new FileWriter(".../writeWithCsvMapWriter.csv", true), CsvPreference.STANDARD_PREFERENCE);

答案 1 :(得分:1)

正如frickskit所指出的:诀窍是添加true作为new FileWriter()的第二个参数,但这也会再次在现有行下添加标题。在您决定将其写出之前,请先使用以下行中的内容检查现有文件中是否存在标题。

public void write(String fileName, List<Map<String, String>> lines) throws IOException {
    final String[] HEADER = new String[] {
        "Column1",
        "Column2",
        "Column3"
    };

    boolean writeHeader = true;

    try (ICsvMapReader mapReader = new CsvMapReader(new FileReader(fileName), CsvPreference.STANDARD_PREFERENCE)) {

        final String[] existingHeader = mapReader.getHeader(true);

        if (Arrays.equals(existingHeader, HEADER)) {
            writeHeader = false;
        }
    } catch (FileNotFoundException ex) {}

    try (ICsvMapWriter mapWriter = new CsvMapWriter(new FileWriter(fileName, true), CsvPreference.STANDARD_PREFERENCE)) {

        final CellProcessor[] processors = getProcessors();

        if (writeHeader) {
            mapWriter.writeHeader(HEADER);
        }

        for (Map<String, String> entry : lines) {
            mapWriter.write(entry, HEADER, processors);
        }
    }
}