build.gradle
// un7z
compile 'org.apache.commons:commons-compress:1.15'
compile 'org.tukaani:xz:1.8'
/**
* 压缩 7z
* @param orgPath
* @param tarPath
*/
static void apache7Z(String orgPath, String tarPath) {
try {
File orgFile = new File(orgPath)
if (!orgFile.exists()) {
return
}
SevenZOutputFile sevenZOutput = new SevenZOutputFile(new File(tarPath))
zip7z(orgFile, sevenZOutput, orgFile.parentFile.path)
sevenZOutput.close()
} catch (IOException e) {
e.printStackTrace()
}
}
static void zip7z(File orgFile, SevenZOutputFile sevenZOutput, String basePath) {
BufferedInputStream bis
if (orgFile.isDirectory()) {
SevenZArchiveEntry entry = sevenZOutput.createArchiveEntry(orgFile, orgFile.path.substring(basePath.length()))
sevenZOutput.putArchiveEntry(entry)
orgFile.listFiles().each {
zip7z(it, sevenZOutput, basePath)
}
} else {
bis = new BufferedInputStream(new FileInputStream(orgFile))
SevenZArchiveEntry entry = sevenZOutput.createArchiveEntry(orgFile, orgFile.path.substring(basePath.length()))
sevenZOutput.putArchiveEntry(entry)
byte[] buffer = new byte[1024]
int len
while ((len = bis.read(buffer)) > 0) {
sevenZOutput.write(buffer, 0, len)
}
sevenZOutput.closeArchiveEntry()
bis.close()
}
}