Java
Java
Add Text Files to a ZIP Using AddString
See more Zip Examples
This example demonstrates how to use the AddString method to add multiple text files directly from string variables into a ZIP archive.
Each string is converted to bytes using the specified character encoding and stored as a separate file entry within the ZIP archive.
This method is useful for dynamically generating small text files such as configuration files, reports, JSON documents, XML, or log files entirely in memory.
Chilkat Java Downloads
import com.chilkatsoft.*;
public class ChilkatExample {
static {
try {
System.loadLibrary("chilkat");
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}
}
public static void main(String argv[])
{
boolean success = false;
CkZip zip = new CkZip();
success = zip.NewZip("stringEntries.zip");
if (success == false) {
System.out.println(zip.lastErrorText());
return;
}
// Add a README text file.
String readmeText = "This ZIP archive was created using AddString.";
success = zip.AddString("docs/readme.txt",readmeText,"utf-8");
if (success == false) {
System.out.println(zip.lastErrorText());
return;
}
// Add a JSON configuration file.
String jsonText = "{ \"server\": \"example.com\", \"port\": 443 }";
success = zip.AddString("config/settings.json",jsonText,"utf-8");
if (success == false) {
System.out.println(zip.lastErrorText());
return;
}
// Add a small XML document.
String xmlText = "<root><status>OK</status></root>";
success = zip.AddString("xml/status.xml",xmlText,"utf-8");
if (success == false) {
System.out.println(zip.lastErrorText());
return;
}
// Write the ZIP archive to disk and close it.
success = zip.WriteZipAndClose();
if (success == false) {
System.out.println(zip.lastErrorText());
return;
}
System.out.println("ZIP archive created successfully.");
}
}