简体   繁体   中英

How to write data into CSV file using only Core Java

I'm trying to implement automation script which should write address information (addrline1,line2,city,state,country,zipcode) into a CSV file. While googling, getting the samples using OpenCSV jar - CSVWriter which I don't need.

Can we achieve this only by using Core Java IO classes? If so, provide some samples.

Thanks,
Karunagara Pandi G

  1. Create a new csv file with a BufferedWriter
  2. If your data is in a collection like ArrayList<String> , just loop over it and do a bufferedWriter.write(line + System.lineSeparator()); for each item on your list

Something like this

//CSV File Writer
public void writeToCSV(ArrayList<String> data) throws Exception {
    try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("data.csv"), StandardCharsets.ISO_8859_1))){
        for(String line : data) {
            writer.write(line + System.lineSeparator());
        }
    }
}

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