我使用以下code解压缩一组文件(包含文件夹):
private boolean unpackZip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
// zapis do souboru
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
// cteni zipu a zapis
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
CodeOutputStream上的代码失败fout = new FileOutputStream(path + filename),错误:
java.io.FileNotFoundException: /storage/emulated/0/BASEFOLDER/FOLDER1/FILE.png
BASEFOLDER已经存在,这是我尝试将文件夹解压缩到的地方。如果我手动(或以编程方式)创建FOLDER1,代码运行正常并成功解压缩。我相信它崩溃了,因为第一个文件(ze)名为FOLDER1 / FILE.png,而FOLDER1尚未创建。我该如何解决这个问题?我知道其他人已经使用过这段代码,我发现它不太可能随机对我不起作用......
答案 0 :(得分:0)
你的AndroidManifest.xml文件中有这个吗?
将写入添加到外部存储权限
uses-permission android:name =“android.permission.WRITE_EXTERNAL_STORAGE”
答案 1 :(得分:0)
我遇到了同样的问题。经过几次调查,我发现了。在代码中添加以下单行:
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
zis.closeEntry(); // <<<<<< ADD THIS LINE
continue;
}
答案 2 :(得分:0)
有时,提取文件已在创建其父目录之前被提取,例如: 文件A位于目录B内。但是未创建目录B,下面列出的文件索引导致了该问题:
因此,要确保在提取文件之前已创建目录,则需要首先创建父目录,例如:
val targetFile = File(tempOutputDir, zipEntry.name)
if (zipEntry.isDirectory) {
targetFile.mkdirs()
} else {
try {
try {
targetFile.parentFile?.mkdirs() // <-- ADD THIS LINE
} catch (exception: Exception) {
Log.e("ExampleApp", exception.localizedMessage, exception)
}
val bufferOutputStream = BufferedOutputStream(
FileOutputStream(targetFile)
)
val buffer = ByteArray(1024)
var read = zipInputStream.read(buffer)
while (read != -1) {
bufferOutputStream.write(buffer, 0, read)
read = zipInputStream.read(buffer)
}
bufferOutputStream.close()
} catch (exception: Exception) {
Log.e("ExampleApp", exception.localizedMessage, exception)
}
}