3
我正在寫一個android應用程序,我需要從幾個文件夾中讀取幾個文件並將它們添加到幾個zip存檔。我需要限制檔案的最大大小,比如16mb。因此,如果文件大小超過16 MB,則在運行時將文件添加到歸檔文件中創建具有相同大小限制的另一個歸檔文件,依此類推。我用下面的包裝類:FileNotFoundException(沒有這樣的文件或目錄)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ChunkedZippedOutputStream {
private ZipOutputStream zipOutputStream;
private String path;
private String name;
private long currentSize;
private int currentChunkIndex;
private final long MAX_FILE_SIZE = 16 * 1000 * 1024; // 16mb limit
private final String PART_POSTFIX = ".part";
private final String FILE_EXTENSION = ".zip";
public ChunkedZippedOutputStream(String path, String name) throws FileNotFoundException {
this.path = path;
this.name = name;
constructNewStream();
}
public void addEntry(ZipEntry entry) throws IOException {
long entrySize = entry.getCompressedSize();
if ((currentSize + entrySize) > MAX_FILE_SIZE) {
closeStream();
constructNewStream();
} else {
currentSize += entrySize;
zipOutputStream.putNextEntry(entry);
}
}
private void closeStream() throws IOException {
zipOutputStream.close();
}
private void constructNewStream() throws FileNotFoundException {
zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(path, constructCurrentPartName())));
currentChunkIndex++;
currentSize = 0;
}
private String constructCurrentPartName() {
// This will give names is the form of <file_name>.part.0.zip, <file_name>.part.1.zip, etc.
StringBuilder partNameBuilder = new StringBuilder(name);
partNameBuilder.append(PART_POSTFIX);
partNameBuilder.append(currentChunkIndex);
partNameBuilder.append(FILE_EXTENSION);
return partNameBuilder.toString();
}
}
,我使用它是這樣的:
String zipPath = Environment.getExternalStorageDirectory() + "/MyApp/MyFolder/Zip/";
String zipName = "MyZipFle";
ChunkedZippedOutputStream zippedOutputStream = new ChunkedZippedOutputStream(zipPath, zipName);
....
zippedOutputStream.addEntry(new ZipEntry("ZipEntry" + i));
但ChunkedZippedOutputStream對象的實例我得到這個錯誤:
java.io.FileNotFoundException: /mnt/sdcard/MyApp/MyFolder/Zip/MyZipFle.part0.zip (No such file or directory)
我知道我在路徑輸入或名稱上做錯了什麼,但我無法弄清楚它是什麼。
此外,如果代碼段是不正確的,請告訴我,我是從這裏How to split a huge zip file into multiple volumes?
如果有一個簡單的解決我的問題,請告訴我。謝謝
您說得對!謝謝 – androidu