6

in my Java program, I would like to use the Apache Commons library to generate the content of a CSV file, but not actually creating the file.

I only want to have the String content of the file, and later, write the file using that content using an existing method.

However in all examples of code, it is necessary to define in the target csv file before hand, giving its path and name, but I don't have it, at this moment of the program flow. Is it possible to just get the String for the future csv file, and handle the real file creation independently? Thank you.

3
  • For what do you need Apache Commons? Can't you just create your string by concatenating your content and write it to a file later on? Commented Dec 2, 2020 at 20:21
  • I did all manually, by string builder, but it's just to apply company's policies with this library, to deal with complex string values, containing special characters, line breaks, etc.. . Thank you for the StringWriter tip. It works. Commented Dec 2, 2020 at 21:41
  • You can use pretty much any implementation of Appendable. Please consider accepting an answer if it answered your question. Commented Dec 3, 2020 at 9:15

1 Answer 1

10

StringWriter

You need the file when you want to write to the file. You could pass the file's content around your programm or store it somewhere until you want to write to the file.

However if you want to write your CSV to String and not to a File you could try to use a StringWriter instead of a FileWriter.

Something like (not compiled, might not be complete)

StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter , CSVFormat.DEFAULT
                .withHeader("Header1", "Header2"));
csvPrinter.printRecord("abc", "ghf");
String csvString = stringWriter.toString();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.