Struct ZipWriter

struct ZipWriter<W: Write + Seek> { ... }

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 cur = std::io::Cursor::new(Vec::new());
let mut zip = ZipWriter::new(&mut cur);

let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
zip.start_file("hello_world.txt", options)?;
zip.write(b"Hello, World!")?;

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

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

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

Implementations

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

fn deep_copy_file(self: &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>>(self: &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: 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, prelude::*};
 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<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(self: &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 [BufWriter], because that has a [Seek::seek] method that implicitly calls [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<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) -> Self

Set automatically large file to true if needed

const fn is_writing_file(self: &Self) -> bool

Returns true if a file is currently open for writing.

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

Set ZIP archive comment.

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

Set ZIP archive comment.

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

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

Get ZIP archive comment.

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

Get ZIP archive comment.

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

fn set_zip64_comment<S>(self: &mut Self, comment: Option<S>)
where
    S: Into<Box<str>>

Set ZIP64 archive comment.

fn set_raw_zip64_comment(self: &mut Self, comment: Option<Box<[u8]>>)

Set ZIP64 archive comment.

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

fn get_zip64_comment(self: &mut Self) -> Option<Result<&str, Utf8Error>>

Get ZIP64 archive comment.

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

Get ZIP 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(self: &mut Self, length: u64, crc32: u32) -> ZipResult<()>

Set the file length and crc32 manually.

Safety

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 abort_file(self: &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>(self: &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 merge_archive<R>(self: &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, prelude::*};
 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>>(self: &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>(self: &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>>(self: &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>(self: &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.

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>(self: &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>(self: &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>>(self: &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: 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 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 shallow_copy_file(self: &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>>(self: &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.

impl<T> Any for ZipWriter<W>

fn type_id(self: &Self) -> TypeId

impl<T> Borrow for ZipWriter<W>

fn borrow(self: &Self) -> &T

impl<T> BorrowMut for ZipWriter<W>

fn borrow_mut(self: &mut Self) -> &mut T

impl<T> From for ZipWriter<W>

fn from(t: T) -> T

Returns the argument unchanged.

impl<T> Same for ZipWriter<W>

impl<T, U> Into for ZipWriter<W>

fn into(self: Self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

impl<T, U> TryFrom for ZipWriter<W>

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

impl<T, U> TryInto for ZipWriter<W>

fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>

impl<W> Freeze for ZipWriter<W>

impl<W> LittleEndianWriteExt for ZipWriter<W>

impl<W> RefUnwindSafe for ZipWriter<W>

impl<W> Send for ZipWriter<W>

impl<W> Sync for ZipWriter<W>

impl<W> Unpin for ZipWriter<W>

impl<W> UnsafeUnpin for ZipWriter<W>

impl<W> UnwindSafe for ZipWriter<W>

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

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

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

fn drop(self: &mut Self)

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

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