반응형
Unzip 관련 작업했을 때 사용했던 테스트 코드입니다.
파일 이름과 경로 부분은 개인적으로 바꿔가며 테스트해 볼 수 있습니다.
package lusotdpot;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.terracotta.agent.repkg.de.schlichtherle.io.FileInputStream;
public class ZipTest {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
//FileInputStream fis = new FileInputStream(new File("...zip"));
File file = new File("...zip");
ZipTest.unzip(getByteArray(file));
}
public static ByteArrayInputStream getByteArray(File file) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(file);
//System.out.println(file.exists() + "!!");
//InputStream in = resource.openStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
//Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
// Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
return new ByteArrayInputStream(bytes);
}
// 2018.04.04 - dwhwang 추가
public static String unzip(ByteArrayInputStream is) {
FileOutputStream fileOutputStream = null;
ZipArchiveInputStream zipInputStream = null;
String storePath = null;
File folder = null;
File newFile = null;
try {
storePath = "...";
folder = new File(storePath);
if(!folder.exists()){
folder.mkdirs();
}
zipInputStream = new ZipArchiveInputStream(is);
ZipArchiveEntry zipEntry = null;
while ((zipEntry = zipInputStream.getNextZipEntry()) != null) {
newFile = new File(storePath + File.separator + zipEntry.getName());
fileOutputStream = new FileOutputStream(newFile);
int length = 0;
while ((length = zipInputStream.read()) != -1) {
fileOutputStream.write(length);
}
//zipInputStream.closeEntry();
fileOutputStream.flush();
fileOutputStream.close();
}
zipInputStream.close();
} catch (Exception e) {
// Exception Handling
e.printStackTrace();
} finally {
try {
//zipInputStream.closeEntry();
fileOutputStream.flush();
fileOutputStream.close();
zipInputStream.close();
} catch (IOException e) {
// Exception Handling
}
}
return storePath;
}
}
반응형
'Programming Language > Java' 카테고리의 다른 글
주석으로 if문 /*/ (0) | 2018.04.11 |
---|---|
(Java) FileOutputStream 실제 사용 예제 (0) | 2018.04.05 |
NullPointerException while using a setter on fragment (0) | 2018.03.09 |
[Java] log4j 사용법 (스크랩) (0) | 2018.01.17 |
[Java] jdk 구버전 다운로드 링크 (0) | 2018.01.15 |