Your achievements

Level 1

0% to

Level 2

Tip /
Sign in

Sign in to Community

to gain points, level up, and earn exciting badges like the new
BedrockMission!

Learn More

View all

Sign in to view all badges

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

Avatar

Avatar
Boost 5
Level 2
keerthana_hn
Level 2

Likes

5 likes

Total Posts

18 posts

Correct Reply

0 solutions
Top badges earned
Boost 5
Boost 3
Boost 1
Validate 1
View profile

Avatar
Boost 5
Level 2
keerthana_hn
Level 2

Likes

5 likes

Total Posts

18 posts

Correct Reply

0 solutions
Top badges earned
Boost 5
Boost 3
Boost 1
Validate 1
View profile
keerthana_hn
Level 2

13-05-2021

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!

Accepted Solutions (0)

Answers (1)

Answers (1)

Avatar

Avatar
Give Back 100
Level 10
asutosh_jena
Level 10

Likes

551 likes

Total Posts

663 posts

Correct Reply

191 solutions
Top badges earned
Give Back 100
Boost 500
Affirm 100
Ignite 1
Establish
View profile

Avatar
Give Back 100
Level 10
asutosh_jena
Level 10

Likes

551 likes

Total Posts

663 posts

Correct Reply

191 solutions
Top badges earned
Give Back 100
Boost 500
Affirm 100
Ignite 1
Establish
View profile
asutosh_jena
Level 10

14-05-2021

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!