欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

JAVA解壓zip和rar文件

周雨萌1年前7瀏覽0評論

JAVA作為一門高級程序設計語言,在處理各種文件操作中具備強大的能力。當我們需要處理zip和rar文件時,一般情況下我們都需要解壓縮文件來進行相關操作。本文就來介紹一下JAVA解壓zip和rar文件的方法。

解壓zip文件:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class UnZipUtil {
public static void unZip(String zipFilePath, String targetPath){
try{
ZipFile zipFile = new ZipFile(new File(zipFilePath));
Enumerationentries = zipFile.entries();
while (entries.hasMoreElements()){
ZipEntry zipEntry = entries.nextElement();
String entryName = zipEntry.getName();
InputStream inputStream = zipFile.getInputStream(zipEntry);
String outFilePath = (targetPath + "/" + entryName).replaceAll("\\*", "/");
File outFile = new File(outFilePath.substring(0, outFilePath.lastIndexOf("/")));
outFile.mkdirs();
if(!outFile.exists()){
outFile.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(outFilePath);
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) >= 0){
outputStream.write(bytes, 0, length);
}
inputStream.close();
outputStream.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}

解壓rar文件:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
public class UnRarUtil {
public static void unRar(String rarFilePath, String targetPath){
try{
ZipFile zipFile = new ZipFile(rarFilePath, "GBK");
Enumerationentries = zipFile.getEntries();
while(entries.hasMoreElements()){
ZipEntry zipEntry = entries.nextElement();
String entryName = zipEntry.getName();
InputStream inputStream = zipFile.getInputStream(zipEntry);
String outFilePath = (targetPath + "/" + entryName).replaceAll("\\*", "/");
File outFile = new File(outFilePath.substring(0, outFilePath.lastIndexOf("/")));
outFile.mkdirs();
if(!outFile.exists()){
outFile.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(outFilePath);
byte[] bytes = new byte[1024];
int length;
while((length = inputStream.read(bytes)) >= 0){
outputStream.write(bytes, 0 ,length);
}
inputStream.close();
outputStream.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void unRarByAnt(String rarFilePath, String targetPath){
Expand expand = new Expand();
expand.setSrc(new File(rarFilePath));
expand.setDest(new File(targetPath));
expand.execute();
}
}

總結:JAVA處理zip和rar文件時,我們可以使用Java自帶的ZipFile類和第三方工具Apache Ant提供的Expand類進行操作。以上代碼分別提供了使用這兩種方法進行zip和rar文件解壓縮的示例代碼。希望對大家有所幫助。