0

I am writing a csv file in a very old java application so i can not use all the new Java 8 streams.

Writer writer = new OutputStreamWriter(new FileOutputStream("file.csv"));
writer.append("data,");
writer.append("data,");

...

Then I need to transform the writer object into a ByteArrayInputStream. How can i do it ?

Thanks in advance. Best regards.

tt0686
  • 1,771
  • 6
  • 31
  • 60

2 Answers2

2

This depends on what you are trying to do.

If you are writing a bunch of data to the file and THEN reading the file you will want to use a FileInputStream in place of your ByteArrayInputStream.

If you want to write a bunch of data to a byte array then you should take a look at using a ByteArrayOutputStream. If you then need to read the byte array as a ByteArrayInputStream you can pass the ByteArrayOutputStream into the input stream like what is shown below. Keep in mind this only works for writing and THEN reading. You can not use this like a buffer.

//Create output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
//Create Writer
Writer writer = new OutputStreamWriter(out);

//Write stuff
...

//Close writer 
writer.close();

//Create input stream using the byte array from out as input.
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
0

Short answer: you can't.

A ByteArrayInputStream is just not assignable from a OutputStreamWriter.

Since you're probably after write, you can just read the file back to a byte[] and then construct a ByteArrayInputStream with it:

    File file = new File("S:\\Test.java");
    FileInputStream fis = new FileInputStream(file);
    byte[] content = new byte[(int) file.length()];
    fis.read(content,0,content.length);
    ByteArrayInputStream bais = new ByteArrayInputStream(content);
maio290
  • 6,440
  • 1
  • 21
  • 38
  • There's no need to use a file though - the `OutputStreamWriter` can wrap a `ByteArrayOutputStream`, and then the OP can construct a `ByteArrayInputStream` from that data. – Jon Skeet Jun 29 '21 at 18:57
  • @JonSkeet I believe OP wants to write to a file first. Otherwise his snippet wouldn't make much sense. If OP doesn't need a file, he'd probably be better of to just use a `StringBuilder` to build the CSV and then get the bytes of the String. – maio290 Jun 29 '21 at 19:04
  • Maybe... it's hard to tell, to be honest. Hopefully this comment thread will be of use to the OP if they actually don't need files... (Actually, the answer from Ryan Williams covers all of this well.) – Jon Skeet Jun 29 '21 at 19:22