Class CompressedFileWriter

java.lang.Object
org.djutils.io.CompressedFileWriter
All Implemented Interfaces:
AutoCloseable

public final class CompressedFileWriter extends Object implements AutoCloseable
File writer for multiple files in to a zip file. Typical use is:
 try (CompressedFileWriter compressedFileWriter = new CompressedFileWriter("CsvData.zip"))
 {
     BufferedWriter bufferedWriter = compressedFileWriter.next("data_2023.csv");
     
     // write data for data_2023
     bufferedWriter.write(...);
     
     compressedFileWriter.next("data_2024.csv");
     
     // write data for data_2024
     bufferedWriter.write(...);
 }
 
If the BufferedWriter is closed, so too is the CompressedFileWriter. Any consumers of the BufferedWriter should thus not close it.

Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved.
BSD-style license. See DJUTILS License.

Author:
Alexander Verbraeck, Peter Knoppers, Wouter Schakel
  • Constructor Details

    • CompressedFileWriter

      public CompressedFileWriter(String file) throws FileNotFoundException
      Constructor.
      Parameters:
      file - String; file, if this does not end with .zip (case insensitive), ".zip" will be appended to it
      Throws:
      FileNotFoundException - if the zip file can not be written
  • Method Details

    • next

      public BufferedWriter next(String name) throws IOException
      Closes the previous file in the zip file, and opens up the next file. The BufferedWriter returned is the same for each call on a CompressedFileWriter.
      Parameters:
      name - String; name of the next file in the zip file
      Returns:
      BufferedWriter; writer to write the next file in to.
      Throws:
      IOException - if no next entry could be created in the zip file
    • close

      public void close() throws IOException
      Specified by:
      close in interface AutoCloseable
      Throws:
      IOException
    • create

      public static BufferedWriter create(String filePath, boolean zipped) throws IOException
      Creates a writer to write data to a file, which can be a zipped file or a regular file. In particular if zipped = true, then with file = "myFile.csv", a file myFile.csv.zip will be created in which a file myFile.csv is located. Writing occurs on this file.
      Parameters:
      filePath - String; path of the file to write; in case of a zipped file, the filename of the zip-file will end with .zip, and the filename in the zip file will be the the filename without .zip.
      zipped - boolean; whether to contain the file in a zip file
      Returns:
      BufferedWriter writer tot write in to
      Throws:
      IOException - on error with filenames, file writing, closing, etc.