I try to add a folder to a zip file but I always get a ZipException
that the zip file is less than the expected size.
val file = File.createTempFile("export_", ".zip")
val zipfile = ZipFile(file)
val tmpFolder = context.cacheDir.absolutePath + "/test"
File(tmpFolder).mkdir()
File(tmpFolder + "/test1.txt").createNewFile()
File(tmpFolder + "/test2.txt").createNewFile()
zipfile.addFolder(File(tmpFolder))
On the last line the ZipException
is raised
E/AndroidRuntime: FATAL EXCEPTION: main
Process: xxxx, PID: 20023
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: net.lingala.zip4j.exception.ZipException: Zip file size less than minimum expected zip file size. Probably not a zip file or a corrupted zip file
at net.lingala.zip4j.headers.HeaderReader.readAllHeaders(HeaderReader.java:69)
at net.lingala.zip4j.ZipFile.readZipInfo(ZipFile.java:1142)
at net.lingala.zip4j.ZipFile.addFolder(ZipFile.java:378)
at net.lingala.zip4j.ZipFile.addFolder(ZipFile.java:365)
at net.lingala.zip4j.ZipFile.addFolder(ZipFile.java:331)
at android.view.View.performClick(View.java:8160)
at android.widget.TextView.performClick(TextView.java:16222)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:8137)
at android.view.View.access$3700(View.java:888)
at android.view.View$PerformClick.run(View.java:30236)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:246)
The files and folders all exist, so why is there an exception?
File.createTempFile("export_", ".zip")
creates a file on disk while File("somefile.zip")
only points to a file but does not create it.
zip4j
seems to check if the file exists and if it exists it expects the file to be a valid zip file. That's why using ZipFile(file)
fails if file
was created with createTempFile()
.