import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class pro {
public static void main(String[] args) {
pro res=new pro();
}
pro(){
compressDirectory("k3.zip"," gdata");
}
public static boolean compressDirectory( String filePath, String directory ) {
File baseFile = new File(filePath);
File file = new File(directory);
ZipOutputStream outZip = null;
try {
outZip = new ZipOutputStream(new FileOutputStream(baseFile));
archive(outZip, baseFile, file);
} catch ( Exception e ) {
return false;
} finally {
if ( outZip != null ) {
try { outZip.closeEntry(); } catch (Exception e) {}
try { outZip.flush(); } catch (Exception e) {}
try { outZip.close(); } catch (Exception e) {}
}
}
return true;
}
public static boolean compressFileList( String filePath, ArrayList<String> fileList ) {
ZipOutputStream outZip = null;
File baseFile = new File(filePath);
try {
outZip = new ZipOutputStream(new FileOutputStream(baseFile));
for ( int i = 0 ; i < fileList.size() ; i++ ) {
File file = new File((String)fileList.get(i));
archive(outZip, baseFile, file, file.getName(), "UTF-8");
}
} catch ( Exception e ) {
return false;
} finally {
if ( outZip != null ) {
try { outZip.closeEntry(); } catch (Exception e) {}
try { outZip.flush(); } catch (Exception e) {}
try { outZip.close(); } catch (Exception e) {}
}
}
return true;
}
private static void archive(ZipOutputStream outZip, File baseFile, File targetFile) {
if ( targetFile.isDirectory() ) {
File[] files = targetFile.listFiles();
for (File f : files) {
if ( f.isDirectory() ) {
archive(outZip, baseFile, f);
} else {
if ( !f.getAbsoluteFile().equals(baseFile) ) {
archive(outZip, baseFile, f, f.getAbsolutePath().replace(baseFile.getParent(), "").substring(1), "Shift_JIS");
}
}
}
}
}
private static boolean archive(ZipOutputStream outZip, File baseFile, File targetFile, String entryName, String enc) {
outZip.setLevel(5);
try {
outZip.putNextEntry(new ZipEntry(entryName));
BufferedInputStream in = new BufferedInputStream(new FileInputStream(targetFile));
int readSize = 0;
byte buffer[] = new byte[1024]; // 読み込みバッファ
while ((readSize = in.read(buffer, 0, buffer.length)) != -1) {
outZip.write(buffer, 0, readSize);
}
// クローズ処理
in.close();
// ZIPエントリクローズ
outZip.closeEntry();
} catch ( Exception e ) {
// ZIP圧縮失敗
return false;
}
return true;
}
}
最終更新:2015年11月08日 08:43