简体   繁体   中英

Write csv file from byte[]

I am getting a file in byte[] which have comma separated values in quotes, I want to save it as CSV by using OpenCSV. I am using this to save it in CSV format.

Following is my code to convert byte[] to array and then store it in file

byte[] bytes = myByteStream.getFile();

String decoded = new String(bytes, "UTF-8");            
//String lines[] = decoded.split("\\r?\\n");


FileOutputStream fos = new FileOutputStream("/home/myPC/Desktop/test.csv"); 
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
CSVWriter writer = new CSVWriter(osw);
String[] row = {decoded};

writer.writeNext(row);
writer.close();
osw.close();

But this above code puts extra quotes around and also merge all lines in one line.

Any help on how to do this properly ?

You can prevent adding quotes to the cell values within the constructor of CSVWriter , for example:

CSVWriter writer = new CSVWriter(osw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

Regarding the whole byte array persisted as a single row. Are you sure there are newlines within the original file.

If so you might get away by doing the following:

    BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "ASCII"));

String line;
while ((line = reader.readLine()) != null) {
    // Handle the line, ideally in a separate method
}

Got this from splitting a byte array on a particular byte

I think Apache Commons CSV is a better CSV library. From the pasted code it is not clear if you want to somehow change the contents of the file or just duplicate it: in the latter case you don't even need to parse the file as CSV records - just copy it byte-for-byte. In the former case, ie if you need to modify the content of the file, you need something like (Commons CSV used here)

CSVParser parser = CSVFormat.newFormat(',').parse(
    new InputStreamReader(new ByteArrayInputStream(bytes), "UTF8"));
CSVPrinter printer = CSVFormat.newFormat(',').print(out);
for (CSVRecord record : parser) {
  try {
    printer.printRecord(record);
  } catch (Exception e) {
    throw new RuntimeException("Error at line "
      + parser.getCurrentLineNumber(), e);
  }
}
parser.close();
printer.close();

Look at the Javadoc for CSVFormat

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