Your issues
Not closing streams
The data like your rows
is written to a buffer (in outputStreamWriter
). Once you flush or close the stream(-writer), it gets piped.
Too much streams/sinks
You just created an empty outputStream
and then (a) write it to another, (b) checking if it is empty. Does that make sense?
var outputStream = new ByteArrayOutputStream();
outputStream.writeTo(fileOutputStream);
At this point you could check your only used final sink fileOutputStream
for bytes that have gotten flushed.
Combining two inputs
From your code, you want to combine two inputs into one output (stream or file). So you are connecting the CSVWriter
to an already filled outputStream
// create final output file and connect a stream as sink: fileOutputStream
String outputFileName = "file.csv"
var fileOutputStream = new FileOutputStream(outputFileName);
// copy first input from given CSV file to sink: fileOutputStream
InputStream inputStream = exportFileOrderTpl.getInputStream();
IOUtils.copy(inputStream, fileOutputStream);
// connect additional CSV input to sink: fileOutputStream
var outputStreamWriter = new OutputStreamWriter(fileOutputStream,StandardCharsets.UTF_8);
var writer = new CSVWriter(outputStreamWriter)
// write rows via CSV to sink: fileOutputStream
String [] rows = {"1","2","3"}
writer.writeNext(rows);
// close writer including connected streams: fileOutputStream
writer.close();
Writing CSV-file using OpenCSV
Like in Baeldungs introduction to OpenCSV's CSVWriter
, you could use the method in given example and slightly modify to write, your single row or many rows to a specified file path:
public void writeRows(List<String[]> stringArray, Path path) throws Exception {
CSVWriter writer = new CSVWriter(new FileWriter(path.toString()));
for (String[] array : stringArray) {
writer.writeNext(array);
}
writer.close();
}
// define your rows consisting of many columns
String[] rowA = {"1","2","3"}
String[] rowB = {"3","4","5"}
List<String[]> rows = List.of(rowA, rowB);
// define your output file
String outputFileName = "file.csv";
Path outputPath = Paths.get(outputFileName);
// write the rows to file by calling the method
writeRows(rows, outputPath)
Note: Only the writer
is used as output-sink. Everything IO-related is handled by OpenCSV. No separate output-streams needed.