Skip to content

Commit b868c70

Browse files
committed
iluwatar#4: Unzip an archive
1 parent 6d538d4 commit b868c70

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/main/java/Library.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import java.util.*;
3535
import java.util.List;
3636
import java.util.zip.ZipEntry;
37+
import java.util.zip.ZipInputStream;
3738
import java.util.zip.ZipOutputStream;
3839

3940
/*
@@ -312,4 +313,28 @@ public static int httpGet(URL address) throws IOException {
312313
HttpURLConnection con = (HttpURLConnection) address.openConnection();
313314
return con.getResponseCode();
314315
}
316+
317+
/**
318+
* UnZip an archive
319+
* @param zipFilename the file name of the archived file
320+
* @throws IOException
321+
*/
322+
public static void unzipArchive(String zipFileName) throws IOException {
323+
byte[] buffer = new byte[1024];
324+
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName))) {
325+
ZipEntry zipEntry = zis.getNextEntry();
326+
while (zipEntry != null) {
327+
String fileName = zipEntry.getName();
328+
File newFile = new File(fileName);
329+
try (FileOutputStream fos = new FileOutputStream(newFile)) {
330+
int len;
331+
while ((len = zis.read(buffer)) > 0) {
332+
fos.write(buffer, 0, len);
333+
}
334+
}
335+
zipEntry = zis.getNextEntry();
336+
}
337+
zis.closeEntry();
338+
}
339+
}
315340
}

src/test/java/LibraryTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,4 +278,19 @@ public void testHttpGet() throws IOException {
278278
int responseCode = Library.httpGet(new URL("http://www.google.com"));
279279
assertEquals(200, responseCode);
280280
}
281+
282+
/**
283+
* Tests for {@link Library#unzipArchive(String)}
284+
*/
285+
@Test
286+
public void testUnzipArchive() throws IOException {
287+
final String archivedFile = "src/test/resources/somearchivedfile.zip";
288+
final String unarchivedFile = "somearchivedfile.txt";
289+
try {
290+
Library.unzipArchive(archivedFile);
291+
assertTrue(Files.exists(Paths.get(unarchivedFile)));
292+
} finally {
293+
Files.deleteIfExists(new File(unarchivedFile).toPath());
294+
}
295+
}
281296
}

0 commit comments

Comments
 (0)