1

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 ?

1
  • Are the rows within the byte array splited by newline? Commented May 31, 2016 at 8:33

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.