Java 如何从zip文件中读取所有文件
我想递归地读取一个zip文件,然后将所有文件解压缩到一个单独的文件夹中 例如,如果Java 如何从zip文件中读取所有文件,java,groovy,zip,Java,Groovy,Zip,我想递归地读取一个zip文件,然后将所有文件解压缩到一个单独的文件夹中 例如,如果some.zip文件包含以下内容: file5.txt somefolder file.txt file4.txt inside.zip file2.txt file3.txt 我想要的只是所有文件,包括zip文件中zip文件中的所有文件(inside.zip,在上面的示例中) somefolder的最终结果是所有文件(我不关心文件夹结构): 我的尝试: 我有下面的代码,但它保持文件夹结构,不打
some.zip
文件包含以下内容:
file5.txt
somefolder
file.txt
file4.txt
inside.zip
file2.txt
file3.txt
我想要的只是所有文件,包括zip文件中zip文件中的所有文件(inside.zip
,在上面的示例中)
somefolder
的最终结果是所有文件(我不关心文件夹结构):
我的尝试:
我有下面的代码,但它保持文件夹结构,不打开zip文件中的zip文件:
import java.util.zip.*
def extractZip (String zipFile) {
def zipIn = new File(zipFile)
def zip = new ZipFile(zipIn)
zip.entries().findAll { !it.directory }.each { e ->
(e.name as File).with{ f ->
f.parentFile?.mkdirs()
f.withOutputStream { w ->
w << zip.getInputStream(e)
}
}
}
}
import java.util.zip*
def extractZip(字符串zipFile){
def zipIn=新文件(zipFile)
def zip=新ZipFile(zipIn)
zip.entries().findAll{!it.directory}.each{e->
(e.name作为文件)。使用{f->
f、 父文件?.mkdirs()
f、 withOutputStream{w->
w
- 遍历条目
- 如果文件不是.zip文件,则将其解压缩
- 如果文件是zip文件,则获取其条目的inputStream。创建新的ZipInputStream。提取流
public void extract(ZipInputStream zipFile, File outputDir) throws IOException
{
ZipEntry entry;
while ( ( entry = zipFile.getNextEntry()) != null)
{
if (entry.isDirectory())
continue;
if (entry.getName().endsWith(".zip"))
{
extract(new ZipInputStream(zipFile), outputDir);
}
else
{
extractToDir(zipFile, new File (outputDir, entry.getName()));
}
}
}
private void extractToDir(ZipInputStream zipFile, File outFile) throws FileNotFoundException
{
ByteStreams.copy(zipFile, new FileOutputStream(outFile));
}
public static void main(String... args)
{
extract(new ZipInputStream(new FileInputStream(zipFileName)), new File("outputPath"));
}
您需要实际测试正在提取的内容,例如,if(正在提取的文件='.zip'){open(正在提取的文件);}
ZipFile是什么?它是自定义类吗?@AlvinBunk import java.util.zip.*@Anthony,在演示示例时应该导入它。如果zip文件有一个文件管理器(如我所示),这不起作用。如果要跳过文件夹,请编辑。如果(entry.isDirectory())继续,只需添加;
public void extract(ZipInputStream zipFile, File outputDir) throws IOException
{
ZipEntry entry;
while ( ( entry = zipFile.getNextEntry()) != null)
{
if (entry.isDirectory())
continue;
if (entry.getName().endsWith(".zip"))
{
extract(new ZipInputStream(zipFile), outputDir);
}
else
{
extractToDir(zipFile, new File (outputDir, entry.getName()));
}
}
}
private void extractToDir(ZipInputStream zipFile, File outFile) throws FileNotFoundException
{
ByteStreams.copy(zipFile, new FileOutputStream(outFile));
}
public static void main(String... args)
{
extract(new ZipInputStream(new FileInputStream(zipFileName)), new File("outputPath"));
}