Struct ZipWriter

pub struct ZipWriter<W: Write + Seek> { /* private fields */ }

ZIP archive generator

Handles the bookkeeping involved in building an archive, and provides an API to edit its contents.

# fn doit() -> zip::result::ZipResult<()>
# {
use zip::ZipWriter;
use std::io::Write;
use zip::write::SimpleFileOptions;

// We use a cursor + vec here, though you'd normally use a `File`
let mut cursor = std::io::Cursor::new(Vec::new());
let mut archive = ZipWriter::new(&mut cursor);

let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
archive.start_file("hello_world.txt", options)?;
archive.write(b"Hello, World!")?;
// also direct write with
// std::io::copy(&mut file, &mut zip)?;

// Apply the changes you've made.
// Dropping the `ZipWriter` will have the same effect, but may silently fail
archive.finish()?;

// raw zip data is available as a Vec<u8>
let zip_bytes = cursor.into_inner();

# Ok(())
# }
# doit().unwrap();

Implementations

impl<A: Read + Write + Seek> ZipWriter<A>

fn new_append(readwriter: A) -> ZipResult<ZipWriter<A>>

Initializes the archive from an existing ZIP archive, making it ready for append.

This uses a default configuration to initially read the archive.

fn new_append_with_config(config: Config, readwriter: A) -> ZipResult<ZipWriter<A>>

Initializes the archive from an existing ZIP archive, making it ready for append.

This uses the given read configuration to initially read the archive.

fn set_flush_on_finish_file(&mut self, flush_on_finish_file: bool)

flush_on_finish_file is designed to support a streaming inner that may unload flushed bytes. It flushes a file's header and body once it starts writing another file. A ZipWriter will not try to seek back into where a previous file was written unless either ZipWriter::abort_file is called while ZipWriter::is_writing_file returns false, or ZipWriter::deep_copy_file is called. In the latter case, it will only need to read previously-written files and not overwrite them.

Note: when using an inner that cannot overwrite flushed bytes, do not wrap it in a std::io::BufWriter, because that has a Seek::seek method that implicitly calls std::io::BufWriter::flush, and ZipWriter needs to seek backward to update each file's header with the size and checksum after writing the body.

This setting is false by default.

impl<A: Read + Write + Seek> ZipWriter<A>

fn deep_copy_file(&mut self, src_name: &str, dest_name: &str) -> ZipResult<()>

Adds another copy of a file already in this archive. This will produce a larger but more widely-compatible archive compared to Self::shallow_copy_file. Does not copy alignment.

fn deep_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>(&mut self, src_path: T, dest_path: U) -> ZipResult<()>

Like deep_copy_file, but uses Path arguments.

This function ensures that the '/' path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file's root.

fn finish_into_readable(self) -> ZipResult<ZipArchive<A>>

Write the zip file into the backing stream, then produce a readable archive of that data.

This method avoids parsing the central directory records at the end of the stream for a slight performance improvement over running [ZipArchive::new()] on the output of [Self::finish()].

 # fn main() -> Result<(), zip::result::ZipError> {
 # #[cfg(any(feature = "deflate-flate2", not(feature = "_deflate-any")))]
 # {
 use std::io::{Cursor, Read, Write};
 use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};

 let buf = Cursor::new(Vec::new());
 let mut zip = ZipWriter::new(buf);
 let options = SimpleFileOptions::default();
 zip.start_file("a.txt", options)?;
 zip.write_all(b"hello\n")?;

 let mut zip = zip.finish_into_readable()?;
 let mut s: String = String::new();
 zip.by_name("a.txt")?.read_to_string(&mut s)?;
 assert_eq!(s, "hello\n");
 # }
 # Ok(())
 # }

impl<W: Write + Seek> ZipWriter<W>

fn get_ref(&self) -> Option<&W>

Gets a reference to the underlying writer in this ZipWriter.

unsafe fn get_mut(&mut self) -> Option<&mut W>

Gets a reference to the underlying writer in this ZipWriter.

Safety

Caller must not corrupt the archive, and must seek back to the current position before continuing to write to the ZipWriter.

impl<W: Write + Seek> ZipWriter<W>

fn new(inner: W) -> ZipWriter<W>

Initializes the archive.

Before writing to this object, the ZipWriter::start_file function should be called. After a successful write, the file remains open for writing. After a failed write, call ZipWriter::is_writing_file to determine if the file remains open.

fn set_auto_large_file(self) -> Self

Set automatically large file to true if needed

const fn is_writing_file(&self) -> bool

Returns true if a file is currently open for writing.

fn set_comment<S>(&mut self, comment: S) -> ZipResult<()>
where
    S: Into<Box<str>>,

Set ZIP archive comment.

fn set_raw_comment(&mut self, comment: Box<[u8]>) -> ZipResult<()>

Set raw ZIP archive comment.

This sets the raw bytes of the comment. The comment is typically expected to be encoded in UTF-8. If the comment is more than u16::MAX it will be truncated

fn get_comment(&self) -> Result<&str, Utf8Error>

Get ZIP archive comment.

const fn get_raw_comment(&self) -> &[u8]

Get raw ZIP archive comment.

This returns the raw bytes of the comment. The comment is typically expected to be encoded in UTF-8.

fn set_raw_zip64_extensible_data_sector(&mut self, extensible_data: Box<[u8]>)

Get the zip64 extensible data. Use at your own risk See 4.3.14.3, 4.3.14.4, 4.4.27 and APPENDIX C of the specification

fn get_raw_zip64_comment(&self) -> Option<&[u8]>

Get raw ZIP64 archive comment.

This returns the raw bytes of the comment. The comment is typically expected to be encoded in UTF-8.

unsafe fn set_file_metadata(&mut self, length: u64, crc32: u32) -> ZipResult<()>

Set the file length and crc32 manually.

Safety

This function assumes that length and crc32 accurately describe the data that has been (or will be) written for the currently open file entry.

The caller must ensure that:

  • A file entry is currently being written (that is, Self::start_file or equivalent has been called successfully and abort_file has not been called since).
  • length is the exact uncompressed size, in bytes, of the file data written to the underlying Write implementation for this entry.
  • crc32 is the correct CRC-32 checksum for that same data, in the format expected by the ZIP specification.

If these requirements are not met, the generated ZIP archive may contain inconsistent or corrupt metadata, which can cause readers to report errors, skip data, or accept data whose integrity cannot be verified.

This overwrites the internal crc32 calculation. It should only be used in case the underlying [Write] is written independently and you need to adjust the zip metadata.

fn hide_file(&mut self, name: &str) -> ZipResult<()>

Removes an entry from the archive's directory without rewriting the archive.

The entry stops appearing in the archive: it is dropped from the central directory written by ZipWriter::finish, so readers no longer see it. Its local header and file data are left in place as unreferenced bytes, which is what makes this cheap — nothing after the removed entry is moved or rewritten, so the cost does not scale with the size of the archive.

The file therefore does not shrink. Reclaiming the space needs a rewrite, which a caller can do when it is worth doing (for example by copying the surviving entries into a fresh archive with ZipWriter::merge_archive) rather than on every removal.

Any entry that shares data with the removed one — see ZipWriter::shallow_copy_file — keeps working, because the bytes it points at are untouched.

If a file is currently being written, it is finished first, exactly as ZipWriter::start_file does.

Safety

.This function only deletes the file entry from the archive's central directory. The file's content remains untouched.

Errors

Returns ZipError::FileNotFound if name does not match an entry.

# fn main() -> Result<(), zip::result::ZipError> {
# #[cfg(any(feature = "deflate-flate2", not(feature = "_deflate-any")))]
# {
use std::io::{Cursor, Write};
use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};

let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
zip.start_file("keep.txt", SimpleFileOptions::default())?;
zip.write_all(b"kept")?;
zip.start_file("drop.txt", SimpleFileOptions::default())?;
zip.write_all(b"dropped")?;
zip.hide_file("drop.txt")?;

let mut archive = ZipArchive::new(zip.finish()?)?;
assert_eq!(archive.len(), 1);
assert!(archive.by_name("keep.txt").is_ok());
assert!(archive.by_name("drop.txt").is_err());
# }
# Ok(())
# }
fn abort_file(&mut self) -> ZipResult<()>

Removes the file currently being written from the archive if there is one, or else removes the file most recently written.

fn start_file<S: ToString, T: FileOptionExtension>(&mut self, name: S, options: FileOptions<'_, '_, T>) -> ZipResult<()>

Create a file in the archive and start writing its contents. The file must not have the same name as a file already in the archive.

The data should be written using the Write implementation on this ZipWriter

fn start_file_with_options<T: FileOptionExtension>(&mut self, options: FileOptions<'_, '_, T>) -> ZipResult<()>

Create a file in the archive and start writing its contents. The file must not have the same name as a file already in the archive. The name need not be UTF-8.

The data should be written using the Write implementation on this ZipWriter

fn merge_archive<R>(&mut self, source: ZipArchive<R>) -> ZipResult<()>
where
    R: Read + Seek,

Copy over the entire contents of another archive verbatim.

This method extracts file metadata from the source archive, then simply performs a single big io::copy() to transfer all the actual file contents without any decompression or decryption. This is more performant than the equivalent operation of calling [Self::raw_copy_file()] for each entry from the source archive in sequence.

 # fn main() -> Result<(), zip::result::ZipError> {
 # #[cfg(any(feature = "deflate-flate2", not(feature = "_deflate-any")))]
 # {
 use std::io::{Cursor, Write, Read};
 use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};

 let buf = Cursor::new(Vec::new());
 let mut zip = ZipWriter::new(buf);
 zip.start_file("a.txt", SimpleFileOptions::default())?;
 zip.write_all(b"hello\n")?;
 let src = ZipArchive::new(zip.finish()?)?;

 let buf = Cursor::new(Vec::new());
 let mut zip = ZipWriter::new(buf);
 zip.start_file("b.txt", SimpleFileOptions::default())?;
 zip.write_all(b"hey\n")?;
 let src2 = ZipArchive::new(zip.finish()?)?;

 let buf = Cursor::new(Vec::new());

 let mut zip = ZipWriter::new(buf);
 zip.merge_archive(src)?;
 zip.merge_archive(src2)?;
 let mut result = ZipArchive::new(zip.finish()?)?;

 let mut s: String = String::new();
 result.by_name("a.txt")?.read_to_string(&mut s)?;
 assert_eq!(s, "hello\n");
 s.clear();
 result.by_name("b.txt")?.read_to_string(&mut s)?;
 assert_eq!(s, "hey\n");
 # }
 # Ok(())
 # }
fn start_file_from_path<E: FileOptionExtension, P: AsRef<Path>>(&mut self, path: P, options: FileOptions<'_, '_, E>) -> ZipResult<()>

Starts a file, taking a Path as argument.

This function ensures that the '/' path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file's root.

fn raw_copy_file_rename<R: Read, S: ToString>(&mut self, file: ZipFile<'_, R>, name: S) -> ZipResult<()>

Add a new file using the already compressed data from a ZIP file being read and renames it, this allows faster copies of the ZipFile since there is no need to decompress and compress it again. Any ZipFile metadata is copied and not checked, for example the file CRC.

use std::fs::File;
use std::io::{Read, Seek, Write};
use zip::{ZipArchive, ZipWriter};

fn copy_rename<R, W>(
    src: &mut ZipArchive<R>,
    dst: &mut ZipWriter<W>,
) -> zip::result::ZipResult<()>
where
    R: Read + Seek,
    W: Write + Seek,
{
    // Retrieve file entry by name
    let file = src.by_name("src_file.txt")?;

    // Copy and rename the previously obtained file entry to the destination zip archive
    dst.raw_copy_file_rename(file, "new_name.txt")?;

    Ok(())
}
fn raw_copy_file_to_path<R: Read, P: AsRef<Path>>(&mut self, file: ZipFile<'_, R>, path: P) -> ZipResult<()>

Like raw_copy_file_to_path, but uses Path arguments.

This function ensures that the '/' path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file's root.

fn raw_copy_file<R: Read>(&mut self, file: ZipFile<'_, R>) -> ZipResult<()>

Add a new file using the already compressed data from a ZIP file being read, this allows faster copies of the ZipFile since there is no need to decompress and compress it again. Any ZipFile metadata is copied and not checked, for example the file CRC.

The name is copied as stored: the same bytes, under the same language encoding flag. So a name in a legacy code page (Shift-JIS, GBK, CP866, ...) stays readable by tools that decode it, where re-encoding the CP437 reading of ZipFile::name as UTF-8 would garble it.

use std::fs::File;
use std::io::{Read, Seek, Write};
use zip::{ZipArchive, ZipWriter};

fn copy<R, W>(src: &mut ZipArchive<R>, dst: &mut ZipWriter<W>) -> zip::result::ZipResult<()>
where
    R: Read + Seek,
    W: Write + Seek,
{
    // Retrieve file entry by name
    let file = src.by_name("src_file.txt")?;

    // Copy the previously obtained file entry to the destination zip archive
    dst.raw_copy_file(file)?;

    Ok(())
}
fn raw_copy_file_touch<R: Read>(&mut self, file: ZipFile<'_, R>, last_modified_time: DateTime, unix_mode: Option<u32>) -> ZipResult<()>

Add a new file using the already compressed data from a ZIP file being read and set the last modified date and unix mode. This allows faster copies of the ZipFile since there is no need to decompress and compress it again. Any ZipFile metadata other than the last modified date and the unix mode is copied and not checked, for example the file CRC.

use std::io::{Read, Seek, Write};
use zip::{DateTime, ZipArchive, ZipWriter};

fn copy<R, W>(src: &mut ZipArchive<R>, dst: &mut ZipWriter<W>) -> zip::result::ZipResult<()>
where
    R: Read + Seek,
    W: Write + Seek,
{
    // Retrieve file entry by name
    let file = src.by_name("src_file.txt")?;

    // Copy the previously obtained file entry to the destination zip archive
    dst.raw_copy_file_touch(file, DateTime::default(), Some(0o644))?;

    Ok(())
}
fn add_directory<S, T: FileOptionExtension>(&mut self, name: S, options: FileOptions<'_, '_, T>) -> ZipResult<()>
where
    S: Into<String>,

Add a directory entry.

As directories have no content, you must not call ZipWriter::write before adding a new file.

fn add_directory_from_path<T: FileOptionExtension, P: AsRef<Path>>(&mut self, path: P, options: FileOptions<'_, '_, T>) -> ZipResult<()>

Add a directory entry, taking a Path as argument.

This function ensures that the '/' path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file's root.

fn finish(self) -> ZipResult<W>

Finish the last file and write all other zip-structures

This will return the writer, but one should normally not append any data to the end of the file. Note that the zipfile will also be finished on drop.

Add a symlink entry.

The zip archive will contain an entry for path name which is a symlink to target.

No validation or normalization of the paths is performed. For best results, callers should normalize \ to / and ensure symlinks are relative to other paths within the zip archive.

WARNING: not all zip implementations preserve symlinks on extract. Some zip implementations may materialize a symlink as a regular file, possibly with the content incorrectly set to the symlink target. For maximum portability, consider storing a regular file instead.

Add a symlink entry, taking Paths to the location and target as arguments.

This function sanitizes both the path and the target. If you don't want to sanitize the path, it's recommended to use the normal Self::add_symlink

This function ensures that the '/' path separator is used and normalizes . and ... It ignores any .. or Windows drive letter

fn add_prepared_file(&mut self, file: PreparedZipFile) -> ZipResult<()>

Add a file whose contents were already compressed by a ZipFileBuilder.

The compressed data is copied into the archive verbatim, so the compression work can be done ahead of time, possibly on another thread. See ZipFileBuilder for an example of parallelizing compression this way. The file must not have the same name as a file already in the archive.

fn shallow_copy_file(&mut self, src_name: &str, dest_name: &str) -> ZipResult<()>

Adds another entry to the central directory referring to the same content as an existing entry. The file's local-file header will still refer to it by its original name, so unzipping the file will technically be unspecified behavior. ZipArchive ignores the filename in the local-file header and treat the central directory as authoritative. However, some other software (e.g. Minecraft) will refuse to extract a file copied this way.

fn shallow_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>(&mut self, src_path: T, dest_path: U) -> ZipResult<()>

Like shallow_copy_file, but uses Path arguments.

This function ensures that the '/' path separator is used and normalizes . and ... It ignores any .. or Windows drive letter that would produce a path outside the ZIP file's root.

impl<W: Write> ZipWriter<StreamWriter<W>>

fn new_stream(inner: W) -> ZipWriter<StreamWriter<W>>

Creates a writer that doesn't require the inner writer to implement [Seek], but where operations that would overwrite previously-written bytes or cause subsequent operations to do so (such as abort_file) will always return an error.

Trait Implementations

impl<W: Write + Seek> Debug for ZipWriter<W>

fn fmt(&self, f: &mut Formatter<'_>) -> Result

impl<W: Write + Seek> Drop for ZipWriter<W>

fn drop(&mut self)

impl<W: Write + Seek> Write for ZipWriter<W>

fn write(&mut self, buf: &[u8]) -> Result<usize>
fn flush(&mut self) -> Result<()>

Auto Trait Implementations

impl<W> !UnwindSafe for ZipWriter<W>

impl<W> Freeze for ZipWriter<W> where GenericZipWriter<W>: Freeze, DeflateCache<W>: Freeze,

impl<W> RefUnwindSafe for ZipWriter<W> where GenericZipWriter<W>: RefUnwindSafe, DeflateCache<W>: RefUnwindSafe,

impl<W> Send for ZipWriter<W> where GenericZipWriter<W>: Send, DeflateCache<W>: Send,

impl<W> Sync for ZipWriter<W> where GenericZipWriter<W>: Sync, DeflateCache<W>: Sync,

impl<W> Unpin for ZipWriter<W> where GenericZipWriter<W>: Unpin, DeflateCache<W>: Unpin,

impl<W> UnsafeUnpin for ZipWriter<W> where GenericZipWriter<W>: UnsafeUnpin, DeflateCache<W>: UnsafeUnpin,

Blanket Implementations

impl<T> Any for ZipWriter<W> where T: 'static + ?Sized,

impl<T> Borrow<T> for ZipWriter<W> where T: ?Sized,

impl<T> BorrowMut<T> for ZipWriter<W> where T: ?Sized,

impl<T> From<T> for ZipWriter<W>

impl<T> Same for ZipWriter<W>

impl<T, U> Into<U> for ZipWriter<W> where U: From<T>,

impl<T, U> TryFrom<U> for ZipWriter<W> where U: Into<T>,

impl<T, U> TryInto<U> for ZipWriter<W> where U: TryFrom<T>,