Java OutStreamWriter to ByteArrayInputStream

1k Views Asked by At

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.

2

There are 2 best solutions below

3
maio290 On

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);
0
Ryan Williams On

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());