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)?
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.
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With