使用 newOutputStream 方法定义文件位置

Making use of newOutputStream method to define file location

以下代码在创建 CSV 文件方面运行良好(仅在下方显示相关代码):

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);
  }

现在,假设我想为此创建一个 zip 文件,我应该如何在这一行 FileOutputStream fos = new FileOutputStream("your_files.zip"); 中使用 dir 变量(我在上述场景中使用的)下面的代码?

我的意思是,我必须定义以下内容:

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();

如果我继续使用 newOutputstream method of Files class,它可能如下所示:

FileOutputStream fos = new FileOutputStream(Files.newOutputStream(dir)); 

这样做正确吗?

我想知道,我应该将 zip 文件的名称放在哪里,我的意思是,我在上一行代码 FileOutputStream("your_files.zip"); 中定义的 your_files.zip

您不需要 FileOutputStream。完全没有。

您只需要一个 OutputStream,这就是 Files.newOutputStream returns:

OutputStream fos = Files.newOutputStream(dir.resolve("your_files.zip"));
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);