Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a csv in a byte[]?

Tags:

java

csv

I would like to know how I should make a method that makes a csv file in a byte[].

At the moment I'm using something like this:

 public byte[] makeCsv(){
      StringBuffer csv= new StringBuffer();
      csv.append("columnheader1;columnheader2\r\n");
      csv.append("cell1;cell2\r\n");
      //...
      return csv.toString().getBytes();
 }

I know I should be using streams but I don't now which ones. Whats the best way to do this(without IO access)?

like image 823
DavidVdd Avatar asked Apr 16 '13 14:04

DavidVdd


People also ask

How many bytes is a CSV?

The amount of data that can be read from a CSV file is up to 200 single-byte characters per cell and up to 640 words per row.

How do I write a byte array to a file?

Java – How to save byte[] to a file write is the simplest solution to save byte[] to a file. // bytes = byte[] Path path = Paths. get("/path/file"); Files. write(path, bytes);

What is byte array example?

A byte array is simply a collection of bytes. The bytearray() method returns a bytearray object, which is an array of the specified bytes. The bytearray class is a mutable array of numbers ranging from 0 to 256.

What is CSV file?

A CSV (comma-separated values) file is a text file that has a specific format which allows data to be saved in a table structured format.


1 Answers

Without IO, your way is just fine. The following is a slight improvement.

  StringBuilder csv= new StringBuilder(); // Faster
  csv.append("columnheader1;columnheader2\r\n");
  csv.append("cell1;cell2\r\n");
  //...
  return csv.toString().getBytes("windows-1252"); // Windows Latin-1

You could use a StringWriter too.

Or write to a ByteArrayOutputStream (in-memory IO) with a PrintWriter.

like image 132
Joop Eggen Avatar answered Sep 29 '22 04:09

Joop Eggen