|
|
Program: How to zip multiple files?
Description: |
Below example shows how to zip multiple files using ZipOutputStream class. putNextEntry()
method starts adding into the zip, and ZipEntry represents a file entry into the zip.
|
Code: |
package com.java2novice.zip;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class MyMultipleFileZip {
public void zipFiles(List<String> files){
FileOutputStream fos = null;
ZipOutputStream zipOut = null;
FileInputStream fis = null;
try {
fos = new FileOutputStream("C:/testing.zip");
zipOut = new ZipOutputStream(new BufferedOutputStream(fos));
for(String filePath:files){
File input = new File(filePath);
fis = new FileInputStream(input);
ZipEntry ze = new ZipEntry(input.getName());
System.out.println("Zipping the file: "+input.getName());
zipOut.putNextEntry(ze);
byte[] tmp = new byte[4*1024];
int size = 0;
while((size = fis.read(tmp)) != -1){
zipOut.write(tmp, 0, size);
}
zipOut.flush();
fis.close();
}
zipOut.close();
System.out.println("Done... Zipped the files...");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try{
if(fos != null) fos.close();
} catch(Exception ex){
}
}
}
public static void main(String a[]){
MyMultipleFileZip mfe = new MyMultipleFileZip();
List<String> files = new ArrayList<String>();
files.add("C:/test.txt");
files.add("C:/test.sh");
files.add("C:/port-chn.txt");
mfe.zipFiles(files);
}
}
|
|
Output: |
Zipping the file: test.txt
Zipping the file: test.sh
Zipping the file: port-chn.txt
Done... Zipped the files...
|
|
|
|
|
List of all java.util.zip class sample examples:- How to compress byte array in java?
- How to decompress byte array in java?
- How to zip a single file?
- How to zip multiple files?
- How to read zip files entries or file name list?
- How to unzip files in java?
- How to generate checksum value for for a file in java?
- How to compress and store objects using zip utility?
- How to decompress the compressed objects using zip utility?
- How to zip a file using ZipFile class?
- How to compress a file in GZip format?
- How to uncompress a file from GZip format?
|
|
|
Transient and Volatile Modifiers
Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state.
Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can
be changed unexpectedly by other parts of the program.
When I do good, I feel good; when I do bad, I feel bad, and that is my religion.
-- Abraham Lincoln
|