Skip to content

Commit

Permalink
#327 Implement Closeable interface on ZipFile
Browse files Browse the repository at this point in the history
  • Loading branch information
srikanth-lingala committed Jun 25, 2021
1 parent 6efc3c3 commit f290b66
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/main/java/net/lingala/zip4j/ZipFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import net.lingala.zip4j.util.RawIO;
import net.lingala.zip4j.util.Zip4jUtil;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -84,7 +85,7 @@
* </ul>
*/

public class ZipFile {
public class ZipFile implements Closeable {

private File zipFile;
private ZipModel zipModel;
Expand Down Expand Up @@ -1076,6 +1077,7 @@ public List<File> getSplitZipFiles() throws ZipException {
*
* @throws IOException when the underlying input stream throws an exception when trying to close it
*/
@Override
public void close() throws IOException {
if (zipFileClosed) {
return;
Expand Down
20 changes: 20 additions & 0 deletions src/test/java/net/lingala/zip4j/MiscZipFileIT.java
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,26 @@ public void testCloseSuccessfullyClosesAllInputStreams() throws IOException {
zipFile.close();

assertThat(inputStreams).hasSize(4);
assertInputStreamsAreClosed(inputStreams);
}

@Test
public void testCloseZipFileByTryWithResourceSuccessfullyClosesAllOpenStreams() throws IOException {
ZipFile zipFile = new ZipFile(generatedZipFile);
zipFile.addFiles(FILES_TO_ADD);
List<InputStream> inputStreams = new ArrayList<>();

try(ZipFile closeableZipFile = new ZipFile(generatedZipFile)) {
for (FileHeader fileHeader : closeableZipFile.getFileHeaders()) {
inputStreams.add(closeableZipFile.getInputStream(fileHeader));
}
}

assertThat(inputStreams).hasSize(3);
assertInputStreamsAreClosed(inputStreams);
}

private void assertInputStreamsAreClosed(List<InputStream> inputStreams) {
for (InputStream inputStream : inputStreams) {
try {
//noinspection ResultOfMethodCallIgnored
Expand Down

0 comments on commit f290b66

Please sign in to comment.