Write CSV to String using opencsv without creating an actual file or a temp file | Community
Skip to main content
Adobe Employee
May 14, 2021
Question

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

  • May 14, 2021
  • 1 reply
  • 1251 views

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!

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

1 reply

Asutosh_Jena_
Community Advisor
Community Advisor
May 14, 2021

Hi @keerthana_h_n 

 

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!