简体   繁体   中英

Reading from a CSV file and writing to a new CSV file using openCSV in java

I'm writing a program which reads a CSV file and I modify some columns.After modifying I have to write it to a new CSV file with modifications.

I have done till reading and modifying but when I'm writing it to a new file I'm just getting a single row.I'm struck here.

Help me overcome this?

I'm using openCSV and language is Java.

My code:

CSVReader reader;
try 
{   
  File file=new File("/home/srinivas/Desktop/saicharan/Cardsmod.csv");
  if(file.createNewFile()){ }
  reader = new CSVReader(new FileReader(filename));
  String filewrite="/home/srinivas/Desktop/saicharan/Cardsmod.csv";   
  CSVWriter writer=new CSVWriter(new FileWriter(filewrite));
  String[] row;
  while((row = reader.readNext()) != null)
  {
    String str=new String();
    String str1=new String();
    for(int i=0;i<row.length;i++)
    {
      str1=str1+","+row[i];
      if(row[i].equals("Card Text Listen"))
      {
        String [] nextLine = reader.readNext();
        String [] nextLine1=reader.readNext();
        str=str+nextLine[i]+nextLine1[i];           
        c2.met(str);
      }
      if(i==11)
      {
        String[] rowwrite=str1.split(",");
        writer.writeNext(rowwrite);                     
      }
    }
  }
  writer.close();
}

Thank You.

I saw you read and write to same file, so you should store all the row to a list and then init the writer after reader completed Exp:

String[] header;
        String[] row;
        int index = 0;
        // processing the header;
        header = reader.readNext();
        for (int i = 0; i < header.length; i++) {
            if (header[i].equals("Card Text Listen")) {
                index = i;
                break;
            }
        }
        // processing data
        while ((row = reader.readNext()) != null) {
            for (int i = 0; i < row.length; i++) {
                if (index == i) {
                    row[i] = "new value";
                    break;
                }
            }
            writer.writeNext(row);
        }

Here is the best efficient way to do it

public void copyCsv(){
    CSVReader reader2 = new CSVReader(new FileReader(ADDRESS_FILE));
    List<String[]> allElements = reader2.readAll();
    CSVWriter writr = new CSVWriter(new FileWriter(Path));
    writr.writeAll(allElements);
    writr.flush();
    writr.close();
}

I made the following application using Sham Khan's answer. Maybe it can work for you. It completely updates the line according to the id in the.csv file.

@Override
public void update(String tableName, Long rowId, List<String> values) {
    List<String> select = select(tableName, rowId);
    if (!select.isEmpty()) {
        select.clear();
        select.add(String.valueOf(rowId));
        select.addAll(values);
        copyCsv(tableName, select, rowId);
    }
}

@SneakyThrows
public void copyCsv(String tableName, List<String> values, Long rowId) {
    CSVReader reader2 = new CSVReader(new FileReader(tableName + ".csv"));
    List<String[]> allElements = reader2.readAll();
    allElements.add(Math.toIntExact(rowId), values.toArray(new String[0]));
    allElements.remove(Math.toIntExact(++rowId));
    CSVWriter writer = new CSVWriter(new FileWriter(tableName + ".csv"));
    writer.writeAll(allElements);
    writer.flush();
    writer.close();
}

 @SneakyThrows
    @Override
    public List<String> select(String tableName, Long rowId) {
        PersonResponseDto personResponseDto = selectById(tableName, rowId);
        if (personResponseDto == null) {
            throw new NotFoundException();
        }
        LinkedList<String> responseValue = new LinkedList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(tableName + ".csv")); CSVParser parser = CSVFormat.DEFAULT.withDelimiter(',').withHeader().parse(br)) {
            for (CSVRecord record : parser) {
                long recordNumber = record.getRecordNumber();
                if (recordNumber == rowId) {
                    Map<String, String> stringStringMap = record.toMap();
                    for (Map.Entry<String, String> m : stringStringMap.entrySet()) {
                        responseValue.add(m.getValue());
                    }
                }
            }
        }
        return responseValue;
    }

@SneakyThrows
@Override
public PersonResponseDto selectById(String tableName, Long rowId) {
    PersonResponseDto responseDto;
    File file = new File(tableName + ".csv");
    try (BufferedReader br = new BufferedReader(new FileReader(file)); CSVParser parser = CSVFormat.DEFAULT.withDelimiter(',').withHeader().parse(br)) {
        Predicate<CSVRecord> predicate = ((record) -> record.get("id").equals(String.valueOf(rowId)));
        responseDto = parser.getRecords().stream().filter(predicate).map(this::preparePersonResponseDto).findFirst().orElseThrow(NotFoundException::new);
    }
    return responseDto;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM