一、基于java原生api实现生成zip和解压zip
1、生成zip
使用到ZipOutputStream
/**
* 生成zip文件
* @throws IOException
* @throws FileNotFoundException
*/
private static void toZip() throws FileNotFoundException, IOException {
String filePath = "D:\\TODO";
try(ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(filePath.concat(File.separator).concat("toZip.zip")))){
List<File> filesList = getAllFiles("D:\\GAME\\RES", new ArrayList<>());
filesList.stream().filter(f->!f.getName().contains(".zip")).forEach(f->{
try {
System.out.println(f.getName());
zos.putNextEntry(new ZipEntry(f.getName()));
zos.write(getFileDataAsByte(f));
zos.closeEntry();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
/**
* file转byte
* @param f
* @return
* @throws IOException
*/
private static byte[] getFileDataAsByte(File f) throws IOException {
InputStream is = new FileInputStream(f);
ByteArrayOutputStream bStream = new ByteArrayOutputStream(1024);
byte[] by = new byte[1024];
int len = -1;
while ((len=is.read(by))!=-1) {
bStream.write(by, 0, len);
}
return bStream.toByteArray();
}
/**
* 获取指定磁盘文件下的所有文件
* @param filePath
* @param filesList
* @return
*/
private static List<File> getAllFiles(String filePath,List<File> filesList) {
File file = new File(filePath);
File[] files=file.listFiles();
for(File f:files) {
if (f.isFile()) {
filesList.add(f);
}
if (f.isDirectory()) {
getAllFiles(f.getAbsolutePath(), filesList);
}
}
return filesList;
}
2、解压zip
使用到ZipOutputStream和ZipFile
/**
* 以zip文件名解压到对应文件夹下面
* @throws IOException
* @throws FileNotFoundException
*/
private static void fromZip() throws FileNotFoundException, IOException {
String zipPath = "D:\\TODO\\toZip.zip";
File file = new File(zipPath);
if(!file.exists()) {
return;
}
try( ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
ZipFile zipFile = new ZipFile(file)){
ZipEntry zipEntry = null;
while ((zipEntry=zis.getNextEntry())!=null) {
System.err.println(zipEntry.getName());
if (!zipEntry.isDirectory()) {
File outFile = new File(
file.getParent()
.concat(File.separator)
.concat(file.getName().substring(0,file.getName().indexOf(".")))
.concat(File.separator)
.concat(zipEntry.getName())
);
if(!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdir();
}
if(!outFile.exists()) {
outFile.createNewFile();
}
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(outFile));
byte b[] = new byte[1024];
int len = -1;
while ((len=bis.read(b))!=-1) {
bos.write(b,0,len);
}
}
}
}
}