I have a file, let's say C:\\source.dat
. I want to compress it into a zip file C:\\folder\\destination.zip
.
I can't find a straightforward example, and the HelloWorld provided with the Maven project doesn't really apply in my case because I'm not writing a plaintext file, so hopefully someone can enlighten me on this.
For reference, the code provided in the example:
@Override
protected int work(String[] args) throws IOException {
// By default, ZIP files use character set IBM437 to encode entry names
// whereas JAR files use UTF-8.
// This can be changed by configuring the respective archive driver,
// see Javadoc for TApplication.setup().
final Writer writer = new TFileWriter(
new TFile("archive.zip/dir/HälloWörld.txt"));
try {
writer.write("Hello world!\n");
} finally {
writer.close();
}
return 0;
}
It's as simple as this:
new TFile("source.dat").cp(new TFile("destination.zip/source.dat"));
For more information, please refer to the Javadoc for the TFile class at http://truezip.java.net/apidocs/de/schlichtherle/truezip/file/TFile.html .
You may also want to try the TrueZIP Archetype File*, which is introduced at http://truezip.java.net/kick-start/index.html . The archetype generates many sample programs which you should explore to get a feel for the API.
This is a straight forward thing to do.
Use
1. ZipOutputStream -- This Class of java This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries.
Offical Docs
http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipOutputStream.html
2. ZipEntry -- This This class is used to represent a ZIP file entry.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/zip/ZipEntry.html
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ConverToZip {
public static void main(String[] args) {
// Take a buffer
byte[] buffer = new byte[1024];
try {
// Create object of FileOutputStream
FileOutputStream fos = new FileOutputStream("C:\\folder\\destination.zip.");
// Get ZipOutstreamObject Object
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry("source.dat");
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream("C:\\source.dat");
int len;
while ((len = in .read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in .close();
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.