Expand my Community achievements bar.

Write CSV to String using opencsv without creating an actual file or a temp file

Avatar

Level 5

Hi all,

 

I'm trying to use the opencsv library to write a csv file. The restriction being that I do not want to create a file on the disk or even a temp file. Is there a way I can achieve it?

From what I looked, the constructor for CSVWriter requires a FileWriter object.

 

Thanks!

1 Reply

Avatar

Community Advisor

Hi @keerthana_hn 

 

I had the similar requirement and used OpenCSV to achieve the use case and with OpenCSV we will need to use the temp path.

File file = new File(tempPath, "fileName");
FileWriter fileWriter = new FileWriter(file);
CSVWriter csvWriter = new CSVWriter(fileWriter, ',', CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
csvWriter.writeAll(dataToWrite);
csvWriter.close();

 

Once the CSV file is generated and processed for your use case you can remove the same file from the temp location:

try {
Files.deleteIfExists(Paths.get(new StringBuilder(tempPath).append("fileName").toString()));
} catch (NoSuchFileException e) {
// NoSuchFileException
} catch (DirectoryNotEmptyException e) {
// DirectoryNotEmptyException
} catch (IOException e) {
// IOException
}

 

Thanks!