我試圖將目錄從一個區域(sdCard/someFolder)
壓縮到第二個目錄(sdCard/Download)
,直到.zip文件大小變爲5mb。然後,我想創建一個新的.zip
文件,填充新文件到5mb等。在Android中使用ZipOutputStream將最多24MB文件壓縮爲.zip
當前,我的代碼成功將文件壓縮到.zip目錄,但其中一個.zip目錄始終損壞。當我的for循環退出22 objects
的第一個Files[]
並開始下一個目錄Files[]
的4 objects
時,我看到了這個。我相信我正在失去一些舊的OutputStreams清理。在for循環的第二次嘗試後,out.putNextEntry()
變爲空。任何幫助就足夠了。
private static void addDirToArchive(ZipOutputStream out, FileOutputStream destinationDir, File sdCardMNDLogs)
{
File[] listOfFiles = sdCardMNDLogs.listFiles();
BufferedInputStream origin = null;
Log.i(TAG3, "Reading directory: " + sdCardMNDLogs.getName());
try{
byte[] buffer = new byte[BUFFER];
for(int i = 0; i < listOfFiles.length; i++)
{
if(listOfFiles[i].isDirectory())
{
addDirToArchive(out, destinationDir, listOfFiles[i]);
continue;
}
try
{
FileInputStream fis = new FileInputStream(listOfFiles[i]);
origin = new BufferedInputStream(fis,BUFFER);
ZipEntry ze = new ZipEntry(listOfFiles[i].getName());
if(currentZipFileSize >= EMAIL_SIZE)
{
out.close();
Log.d(emailTAG, "Creating new zipfile: /Download/MND/nwdLogs_" + i);
out = new ZipOutputStream(new FileOutputStream(new File(sdCard.getAbsolutePath() + "/Download/MND/nwdLogs_ " + i + ".zip")));
currentZipFileSize = 0;
}
out.putNextEntry(ze);
int length;
Log.i(TAG3, "Adding file: " + listOfFiles[i].getName());
while((length = origin.read(buffer, 0, BUFFER)) != -1)
{
out.write(buffer, 0, length);
}
out.closeEntry();
origin.close();
currentZipFileSize = currentZipFileSize + ze.getCompressedSize();
}
catch(IOException ioe)
{
Log.e(TAG3, "IOException: " + ioe);
}
}
}
finally
{
try {
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
FileOutputStream destinationDir = new FileOutputStream(sdCard.getAbsolutePath() + "/Download/Dir/nwdLogs.zip");
ZipOutputStream out = new ZipOutputStream(destinationDir);
currentZipFileSize = 0;
addDirToArchive(out, destinationDir, dirName);
out.close();
destinationDir.close();
我在創建新的ZipOutputStream之前以及在初始調用addDirToArchive(out,destinationDir,dirName)之前缺少out.close()。謝謝。 –
現在我遇到了包含兩個文件夾和兩個文件的原始目錄不能正確讀取的問題。該程序將壓縮文件[]中的第一個目錄,但由於錯誤而未壓縮其他三個目錄:流被關閉。 –