import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.io.FileUtils;
public class Main {
private int pathLength;
public Main(String archiverName, File archiveFile, File file) throws Exception {
super();
if (file.isDirectory()) {
pathLength = file.getPath().length();
pathLength++;
} else {
pathLength = file.getParentFile().getPath().length();
}
ArchiveStreamFactory asf = new ArchiveStreamFactory();
FileOutputStream fos = new FileOutputStream(archiveFile);
ArchiveOutputStream aos = asf.createArchiveOutputStream(archiverName, fos);
try {
addFile(file, aos);
} finally {
aos.close();
fos.close();
}
}
private void addFile(File f, ArchiveOutputStream aos)
throws IOException {
if (f.isDirectory()) {
File[] files = f.listFiles();
for (File f2 : files) {
addFile(f2, aos);
}
} else {
String path = f.getPath();
if (path.length() > pathLength) {
path = path.substring(pathLength);
}
ArchiveEntry entry = aos.createArchiveEntry(f, path);
aos.putArchiveEntry(entry);
aos.write(FileUtils.readFileToByteArray(f));
aos.closeArchiveEntry();
}
}
public static void main(String[] args) throws Exception {
String archiveFile = args[0]; // Create Archive File
String file = args[1]; // Add to Archive File
String ext = archiveFile.substring(archiveFile.lastIndexOf('.') + 1);
new Main(ext, new File(archiveFile), new File(file));
}
}
2009年6月5日
Apache Commons Compress Create Archive File
Apache Commons Compress
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言