I've the following code working fine in terms of CSV file creation (only showing relevant code below):
rsCompany = pstmtCompany.executeQuery();
Path dir = Paths.get("/srv/custom_users", userName);
Files.createDirectories(dir);
Path filecompany = dir.resolve("company_custom_file_" + unixTimestamp + ".csv");
try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(filecompany))) {
writer.writeAll(rsCompany, true);
}
Now, let's say I want to create a zip file for the same, how should I make use of the dir
variable (that I used in the above scenario) in this line FileOutputStream fos = new FileOutputStream("your_files.zip");
of code below?
I mean, I have to define the following things:
Path dir = Paths.get("/srv/custom_users", userName);
Files.createDirectories(dir);
FileOutputStream fos = new FileOutputStream("your_files.zip");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);
ZipEntry entry = new ZipEntry(file.getFileName().toString());
zos.putNextEntry(entry);
try (CSVWriter writer = new CSVWriter(new OutputStreamWriter(zos,StandardCharsets.UTF_8)))) {
writer.writeAll(rsDemo, true);
writer.flush();
zos.closeEntry();
}
zos.close();
If I go ahead and use newOutputstream
method of Files
class, it may looks like the following :
FileOutputStream fos = new FileOutputStream(Files.newOutputStream(dir));
Is it a correct way to go about it?
I'm wondering, where should I place the name of the zip file , I mean, your_files.zip
that I defined in my previous line of code FileOutputStream("your_files.zip");
?
You don’t need a FileOutputStream. At all.
You only need an OutputStream, and that is what Files.newOutputStream returns:
OutputStream fos = Files.newOutputStream(dir.resolve("your_files.zip"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);