java

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Due to business needs, recently used file compression decompression and compression file function, find a lot of good example on the Internet, reference predecessors achievements, with a bit of their own needs, the realization of recursive zip file decompression
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.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
* Function: use Apache Ant to provide org.apache.tools.zip to achieve zip compression and decompression (support Chinese file name)
* To solve the problem of java.util.zip package does not support Chinese characters. The java.util.zip packet is used, when there is a name for the zip file when the file Chinese,
* There would appear abnormal:"Exception in thread "main " java.lang.IllegalArgumentException at
* java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285)
*
*/
public class AntZipUtil {
private static List list = new ArrayList();
private static Logger log = Logger.getLogger(AntZipUtil.class);

private static List listFile(String path) {
File file = new File(path);
String[] array = null;
String sTemp = "";
if (!file.isDirectory()) {
return null;
}
array = file.list();
if (array.length > 0) {
for (int i = 0; i <array.length; i++) {
sTemp = path + array[i];
file = new File(sTemp);
if (file.isDirectory()) {
listFile(sTemp + "/");
} else
list.add(sTemp);
}
} else {
return null;
}
return list;
}

public static void zip(String needtozipfilepath, String zipfilepath) {
try {
byte[] b = new byte[512];
File needtozipfile = new File(needtozipfilepath);
if (!needtozipfile.exists()) {
System.err.println("To compress the file or directory specified does not exist.");
return;
}
String zipFile = zipfilepath;
File targetFile = new File(zipFile.substring(0,
zipFile.indexOf("\\") + 1));
if (!targetFile.exists()) {
System.out.println("The target file or directory specified does not exist.");
return;
}
String filepath = needtozipfilepath;
List fileList = listFile(filepath);
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cs = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
cs));
for (int i = 0; i <fileList.size(); i++) {
InputStream in = new FileInputStream((String) fileList.get(i));
String fileName = ((String) fileList.get(i)).replace(
File.separatorChar, '/');
fileName = fileName.substring(fileName.indexOf("/") + 1);
ZipEntry e = new ZipEntry(fileName);
out.putNextEntry(e);
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.closeEntry();
}
out.close();
} catch (Exception e) {
log.error("", e);
}
}

/**
* Compressed file or folder
*
* @param baseDirName
*            Root compression
* @param fileName
*            The root directory of the compressed file or folder name
* @param targetFileName
*            The target ZIP file asterisk "*" represents all the files under the root directory
*
*/
public static boolean zip(String baseDirName, List fileNames,
String targetFileName, String encoding) {
boolean flag = false;
try {
// To judge whether the "compression of the root directory" whether there is a folder!!
File baseDir = new File(baseDirName);
if (!baseDir.exists() || (!baseDir.isDirectory())) {
System.err.println("Compression failure root directory does not exist!: " + baseDirName);
return false;
}
// The absolute path to get this "compression of the root directory"
String baseDirPath = baseDir.getAbsolutePath();
// By the "ZIP file" file name to get a compressible ZipOutputStream
File targetFile = new File(targetFileName);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
targetFile));
// Chinese garbled, retrofit the introduction of the following
// CnZipOutputStream out = new CnZipOutputStream(new
// FileOutputStream(targetFile),encoding);
// Set the compression coding Apache Ant has a package deal specifically with the ZIP file, you can specify a file name encoding. This problem can be solved. For example:
// Org.apache.tools.zip.ZipOutputStream instead of java.util.zip.ZipOutputStream. ZipOutputStream
// out = .....; out.setEncoding("GBK");
// out.setEncoding("GBK");//Set to GBK in the windows will not garbled, if placed in the Linux or Unix is not set
out.setEncoding(encoding);
// "*" Said all the documents including compression root directory baseDirName, to the targetFileName file
if (fileNames.equals("*")) {
AntZipUtil.dirToZip(baseDirPath, baseDir, out);
} else {
File[] files = new File[fileNames.size()];
for (int i = 0; i <fileNames.size(); i++) {
// Abstract parent path and child path name string to create a new File instance according to.
files[i] = new File(baseDir, (String) fileNames.get(i));
}
if (files[0].isFile()) {
// A static method for the class to compress a file
// CompressUtil.fileToZip(baseDirPath, file, out);
AntZipUtil.filesToZip(baseDirPath, files, out);
}
}
out.close();
flag = true;
} catch (FileNotFoundException e) {
log.error("", e);
} catch (IOException e) {
log.error("", e);
}
return flag;
}

/**
* Files will be compressed to the Zip output stream
*
* @param baseDirPath
*            Root directory path
* @param file
*            To compress the file
* @param out
*            The output stream
* @throws IOException
*/
private static void fileToZip(String baseDirPath, File file,
ZipOutputStream out) throws IOException {
FileInputStream in = null;
org.apache.tools.zip.ZipEntry entry = null;
// Create a copy buffer of 1024*4 = 4K
byte[] buffer = new byte[1024 * 4];
int bytes_read = 0;
if (file.isFile()) {
in = new FileInputStream(file);
// The parent path name string and child path name string to create a new File instance according to
String zipFileName = getEntryName(baseDirPath, file);
entry = new org.apache.tools.zip.ZipEntry(zipFileName);
// "Compressed file "object into a file to compress" object "
out.putNextEntry(entry);
// Now is the "file to compress" object content written into the "archive" object
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
in.close();
}
}

/**
* Compression of multiple file directory to the Zip output stream
*
* @param baseDirPath
* @param files
* @param out
* @throws IOException
*/
@SuppressWarnings("unused")
private static void filesToZip(String baseDirPath, File[] files,
ZipOutputStream out) throws IOException {
// Traversal of all the documents on a compression
for (int i = 0; i <files.length; i++) {
File file = files[i];
if (file.isFile()) {
// A static method for the class to compress a file
AntZipUtil.fileToZip(baseDirPath, file, out);
} else {
/*
* This is a folder so to get it again all of the following files here is to call their own..... Recursive....
*/
AntZipUtil.dirToZip(baseDirPath, file, out);
}
}
}

/**
* The file directory compression to the Zip output stream
*
* @param baseDirPath
* @param dir
* @param out
* @throws IOException
*/
private static void dirToZip(String baseDirPath, File dir,
ZipOutputStream out) throws IOException {
// Get a list of files (the set of all file object in the directory)
File[] files = dir.listFiles();
// If the document set the length of the array is 0, it is proved that this is an empty folder, although there was no need to recycle traverse it, but also want to take this empty folders compressed to the target file.
if (files.length == 0) {
// The parent path name string and child path name string to create a new File instance according to
String zipFileName = getEntryName(baseDirPath, dir);
org.apache.tools.zip.ZipEntry entry = new org.apache.tools.zip.ZipEntry(
zipFileName);
out.putNextEntry(entry);
out.closeEntry();
} else {
// Traversal of all the documents on a compression
for (int i = 0; i <files.length; i++) {
File file = files[i];
if (file.isFile()) {
// A static method for the class to compress a file
AntZipUtil.fileToZip(baseDirPath, file, out);
} else {
/*
* This is a folder so to get it all of the following files again
* Here is the call their own..... Recursive....
*/
AntZipUtil.dirToZip(baseDirPath, file, out);
}
}
}
}

/**
* To obtain the compressed files in the ZIP file name entry, which is relative to the root directory path name
*
* @param baseDirPath
*            The root directory
* @param file
* @return
*/
private static String getEntryName(String baseDirPath, File file) {
/**
* Change the baseDirPath of the form "C:/temp" into "C:/temp/"
*/
if (!baseDirPath.endsWith(File.separator)) {
baseDirPath += File.separator;
}
String filePath = file.getAbsolutePath();
/**
* To test whether this abstract pathname represents the file is a directory. If the file is a directory must turn back with "/" the file object is similar to the
* "C:/temp/Human portrait /1.jpg "if this file is a folder then must turn back with "/"
* Because if you don't do this, it will be compressed to the target file but not positive solutions show that the operating system can not be correctly identified by its file type (a file or folder)
*/
if (file.isDirectory()) {
filePath += "/";
}
int index = filePath.indexOf(baseDirPath);
return filePath.substring(index + baseDirPath.length());
}

////////////////////////////Decompression////////////////////////////////////////
/**
* Org.apache.tools.zip calls to achieve decompression, support nested and Chinese directory name
* You can also use java.util.zip but if it is Chinese words, decompression when the file name will be garbled
* . The reason is coded character decompression software code format with the java.util.zip.ZipInputStream set (fixed UTF-8) different
*
* @param zipFileName
*            To decompress the file
* @param outputDirectory
*            To extract to the directory
* @throws Exception
*/
public static boolean unZip(String zipFileName, String outputDirectory) {
boolean flag = false;
try {
org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(
zipFileName, "GBK");
java.util.Enumeration e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
while (e.hasMoreElements()) {
zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
if (zipEntry.isDirectory()) {
String name = zipEntry.getName().toLowerCase();
name = name.substring(0, name.length() - 1);

File f = new File(outputDirectory + File.separator + name);
f.mkdir();
List fileList = FileUtil.refreshFileList(outputDirectory
+ File.separator + name);
for (int i = 0; i <fileList.size(); i++) {
String ffSt = (String) fileList.get(i);
unZip(ffSt, outputDirectory);
}

log.info("Create a directory: " + outputDirectory + File.separator + name);
} else {
String fileName = zipEntry.getName();
fileName = fileName.replace('\\', '/');
if (fileName.indexOf("/") != -1) {
createDirectory(outputDirectory, fileName.substring(0,
fileName.lastIndexOf("/")));
fileName = fileName.substring(
fileName.lastIndexOf("/") + 1,
fileName.length());
}
File f = new File(outputDirectory + File.separator
+ zipEntry.getName());
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);

byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
out.close();
in.close();
if (StringUtils.endsWith(zipEntry.getName(), ".zip")) {
String str = outputDirectory + "/" + zipEntry.getName();
unZip(str, outputDirectory);
}
}
flag = true;
}
} catch (Exception e) {
log.error("", e);
}
return flag;
}

/**
* Create a directory
*
* @param directory
*            The parent directory
* @param subDirectory
*            Sub directory
*/
private static void createDirectory(String directory, String subDirectory) {
String dir[];
File fl = new File(directory);
try {
if (subDirectory == "" && fl.exists() != true)
fl.mkdir();
else if (subDirectory != "") {
dir = subDirectory.replace('\\', '/').split("/");
for (int i = 0; i <dir.length; i++) {
File subFile = new File(directory + File.separator + dir[i]);
if (subFile.exists() == false)
subFile.mkdir();
directory += File.separator + dir[i];
}
}
} catch (Exception e) {
log.error("", e);
}
}
}

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
*
* @author HLW
* @date 2013-10-25
*/
public class FileUtil {
/**
* Ergodic designated folder file
*
* @param strPath
* @return
*/
public static List refreshFileList(String strPath) {
List filelist = new ArrayList();
File dir = new File(strPath);
File[] files = dir.listFiles();

if (files != null) {

for (int i = 0; i <files.length; i++) {
if (files[i].isDirectory()) {
refreshFileList(files[i].getAbsolutePath());

} else {
String strFileName = files[i].getAbsolutePath();
filelist.add(strFileName);
}
}
}
return filelist;
}
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Beacher at December 14, 2013 - 4:11 PM