Unzip *.docx file in memory without write to disk - Java - java

I want to unzip *.docx file in memory without to write the output to the disk. I found the following implementation but it allows only to read the compressed files but not to see the directory structure. It is important for me to know the location of each file in the directory tree. can somebody give me a direction?
private static void UnzipFileInMemory() {
try {
ZipFile zf = new ZipFile("d:\\a.docx");
int i = 0;
for (Enumeration e = zf.entries(); e.hasMoreElements();) {
InputStream in = null;
try {
ZipEntry entry = (ZipEntry) e.nextElement();
System.out.println(entry);
in = zf.getInputStream(entry);
} catch (IOException ex) {
//Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
//Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} catch (IOException ex) {
//Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
}
}

Use ZipInputStream : zEntry in this example gives you file location.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class unzip {
public static void main(String[] args) {
String filePath = "D:/Tmp/Tmp.zip";
String oPath = "D:/Tmp/";
new unzip().unzipFile(filePath, oPath);
}
public void unzipFile(String filePath, String oPath) {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
try {
fis = new FileInputStream(filePath);
zipIs = new ZipInputStream(new BufferedInputStream(fis));
while ((zEntry = zipIs.getNextEntry()) != null) {
try {
FileOutputStream fos = null;
String opFilePath = oPath + zEntry.getName();
fos = new FileOutputStream(opFilePath);
System.out.println(zEntry.getName());
fos.flush();
fos.close();
} catch (Exception ex) {
}
}
zipIs.close();
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

You associate the zip format file as a virtual file system (FileSystem). For that java already has a protocol handler, for jar:file://.... So you have to prepend a File.toURI() with "jar:".
URI docxUri = ,,, // "jar:file:/C:/... .docx"
Map<String, String> zipProperties = new HashMap<>();
zipProperties.put("encoding", "UTF-8");
try (FileSystem zipFS = FileSystems.newFileSystem(docxUri, zipProperties)) {
Path documentXmlPath = zipFS.getPath("/word/document.xml");
Now you may use Files.delete() or Files.copy between real disk filesystem and zip.
When using XML:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(Files.newInputStream(documentXmlPath));
//Element root = doc.getDocumentElement();
You can then use XPath to find the places, and write the XML back again.
It even might be that you do not need XML but could replace place holders:
byte[] content = Files.readAllBytes(documentXmlPath);
String xml = new String(content, StandardCharsets.UTF_8);
xml = xml.replace("#DATE#", "2014-09-24");
xml = xml.replace("#NAME#", StringEscapeUtils.escapeXml("Sniper")));
...
content = xml.getBytes(StandardCharsets.UTF_8);
Files.delete(documentXmlPath);
Files.write(documentXmlPath, content);
For a fast development, rename a copy of the .docx to a name with the .zip file extension, and inspect the files.

Simply add a file checking code within your loop:
if (!entry.isDirectory()) // Alternatively: if(entry.getName().contains("."))
System.out.println(entry);

Related

How to download chosen file from ftp-server using java? [duplicate]

With this code iI always get a empty file.
What I have to do with it?
login is always true. (ofc, here is not real password)
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import java.io.*;
public class Logs {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("myac.cs-server.pro", 121);
boolean login = client.login("a3ro", "passWordIsSecret");
System.out.println(login);
String remoteFile1 = "myac_20150304.log";
File downloadFile1 = new File("C:\\Users\\Aero\\Desktop\\test\\myac.log");
OutputStream outputStream1 =
new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = client.retrieveFile(remoteFile1, outputStream1);
System.out.println(success);
outputStream1.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Use FileOutputStream:
String filename = "test.txt";
FileOutputStream fos = new FileOutputStream(filename);
client.retrieveFile("/" + filename, fos);
Use something like this:
InputStream inputStream = client.retrieveFileStream(remoteFileNameHere);
To retrieve the remote file input stream.
Then you can use to copy the stream to desired file:
FileOutputStream out = new FileOutputStream(targetFile);
org.apache.commons.io.IOUtils.copy(in, out);

Unzip files in FTP server using Java

I am trying to unzip files in the FTP location, but when i unzip i am not able to get all the files in FTP server, but when i try the code to unzip files to local machine it is working. I am sure somewhere while writing the data to FTP i am missing something.Below is my code. Please help me on this.
public void unzipFile(String inputFilePath, String outputFilePath) throws SocketException, IOException {
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
InputStream in = null;
FTPClient ftpClientinput = new FTPClient();
FTPClient ftpClientoutput = new FTPClient();
String ftpUrl = "ftp://%s:%s#%s/%s;type=i";
ftpClientinput.connect(server, port);
ftpClientinput.login(user, pass);
ftpClientinput.enterLocalPassiveMode();
ftpClientinput.setFileType(FTP.BINARY_FILE_TYPE);
String uploadPath = "path";
ftpClientoutput.connect(server, port);
ftpClientoutput.login(user, pass);
ftpClientoutput.enterLocalPassiveMode();
ftpClientoutput.setFileType(FTP.BINARY_FILE_TYPE);
try {
// fis = new FileInputStream(inputFilePath);
String inputFile = "/Srikanth/RecordatiFRA_expenses.zip";
String outputFile = "/Srikanth/FR/";
in = ftpClientinput.retrieveFileStream(inputFile);
zipIs = new ZipInputStream(new BufferedInputStream(in));
while ((zEntry = zipIs.getNextEntry()) != null) {
try {
byte[] buffer = new byte[4 * 8192];
FileOutputStream fos = null;
OutputStream out = null;
// String opFilePath = outputFilePath + zEntry.getName();
String FTPFilePath = outputFile + zEntry.getName();
// System.out.println("Extracting file to "+opFilePath);
System.out.println("Extracting file to " + FTPFilePath);
// fos = new FileOutputStream(opFilePath);
out = ftpClientoutput.storeFileStream(FTPFilePath);
// System.out.println(out);
int size;
while ((size = zipIs.read(buffer, 0, buffer.length)) != -1) {
// fos.write(buffer, 0 , size);
out.write(buffer, 0, size);
}
// fos.flush();
// fos.close();
} catch (Exception ex) {
ex.getMessage();
}
}
zipIs.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ftpClientinput.isConnected()) {
ftpClientinput.logout();
ftpClientinput.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This method will do what you want, you can tweak it as you like.
I cleaned up and removed a lot that you didn't need; One thing to note is the use of try-with-resources blocks and not declaring your local variables so far from where they're used.
Your main error was that you needed to call completePendingCommand after certain methods as noted in their documentation.
Remember to read the documentation on methods you're using for the first time.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public static void unzipFTP(String server, int port, String user, String pass, String ftpPath)
throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect(server, port);
ftp.login(user, pass);
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
try (InputStream ftpIn = ftp.retrieveFileStream(ftpPath);
ZipInputStream zipIn = new ZipInputStream(ftpIn);) {
// complete and verify the retrieve
if (!ftp.completePendingCommand()) {
throw new IOException(ftp.getReplyString());
}
// make the output un-zipped directory, should be unique sibling of the target zip
String outDir = ftpPath + "-" + System.currentTimeMillis() + "/";
ftp.makeDirectory(outDir);
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
throw new IOException(ftp.getReplyString());
}
// write the un-zipped entries
ZipEntry zEntry;
while ((zEntry = zipIn.getNextEntry()) != null) {
try (OutputStream out = ftp.storeFileStream(outDir + zEntry.getName());) {
zipIn.transferTo(out);
}
if (!ftp.completePendingCommand()) {
throw new IOException(ftp.getReplyString());
}
}
} finally {
try {
if (ftp.isConnected()) {
ftp.logout();
ftp.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

How to copy file in resource folder in java

Need a quick help. I am new to Java..In my project I have input & output folder in resources. Inside input folder I have a csv file. I need to move that file to output folder through java code. How to copy that input file to output directory. I have tried in google but not getting a working solution. My project structure is based on standard maven project.
I think there are at least four methods you can use to move your csv file to some other directory.
I assume that you already know the absolute directory path.
Method 1. The way of apache commons
You can use apache commons io library.
public static void moveWithApacheCommonsIO()
{
File sourceFile = new File("resource/AssetsImportCompleteSample.csv");
File destinationFile = new File("resource/aa/AssetsImportCompleteSample.csv");
try {
FileUtils.moveFile(sourceFile, destinationFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Method 2. The way of java's NIO
You can also use nio (non-blocking io) in java
public static void moveWithFileNIO()
{
File sourceFile = new File("resource/AssetsImportCompleteSample.csv");
File destinationFile = new File("resource/aa/AssetsImportCompleteSample.csv");
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
sourceFile.deleteOnExit();
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final FileChannel inChannel = inputStream.getChannel();
final FileChannel outChannel = outputStream.getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
inChannel.close();
outChannel.close();
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Method 3. The traditional way of java's IO
You can use traditional method with file in and output stream in java.(Blocking IO)
public static void moveWithFileInOutStream()
{
File sourceFile = new File("resource/AssetsImportCompleteSample.csv");
File destinationFile = new File("resource/aa/AssetsImportCompleteSample.csv");
InputStream fin = null;
OutputStream fout = null;
sourceFile.deleteOnExit();
try {
fin = new BufferedInputStream(new FileInputStream(sourceFile));
fout = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte[] readBytes = new byte[1024];
int readed = 0;
while((readed = fin.read(readBytes)) != -1)
{
fout.write(readBytes, 0, readed);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
fin.close();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Method 4. Using JNI(Java Native Interface)
Finally, you can use some function like mv or MovFile depending on your Operating system with JNI.
I think it is out of scope of this topic. you can google it or see JNA library to accomplish your task if you want.
Here are complete code for you.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import org.apache.commons.io.FileUtils;
public class MovefileTest {
public static void moveWithApacheCommonsIO()
{
File sourceFile = new File("resource/AssetsImportCompleteSample.csv");
File destinationFile = new File("resource/aa/AssetsImportCompleteSample.csv");
try {
FileUtils.moveFile(sourceFile, destinationFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void moveWithFileInOutStream()
{
File sourceFile = new File("resource/AssetsImportCompleteSample.csv");
File destinationFile = new File("resource/aa/AssetsImportCompleteSample.csv");
InputStream fin = null;
OutputStream fout = null;
sourceFile.deleteOnExit();
try {
fin = new BufferedInputStream(new FileInputStream(sourceFile));
fout = new BufferedOutputStream(new FileOutputStream(destinationFile));
byte[] readBytes = new byte[1024];
int readed = 0;
while((readed = fin.read(readBytes)) != -1)
{
fout.write(readBytes, 0, readed);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
fin.close();
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void moveWithFileNIO()
{
File sourceFile = new File("resource/AssetsImportCompleteSample.csv");
File destinationFile = new File("resource/aa/AssetsImportCompleteSample.csv");
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
sourceFile.deleteOnExit();
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final FileChannel inChannel = inputStream.getChannel();
final FileChannel outChannel = outputStream.getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
inChannel.close();
outChannel.close();
inputStream.close();
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//moveWithApacheCommonsIO();
//moveWithFileNIO();
moveWithFileInOutStream();
}
}
Regards,

How to get file summary information with Java/Apache POI

i'am trying to get the summary information from file with JAVA and I can't found anything. I tried with org.apache.poi.hpsf.* .
I need Author, Subject, Comments, Keywords and Title.
File rep = new File("C:\\Cry_ReportERP006.rpt");
/* Read a test document <em>doc</em> into a POI filesystem. */
final POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream(rep));
final DirectoryEntry dir = poifs.getRoot();
DocumentEntry dsiEntry = null;
try
{
dsiEntry = (DocumentEntry) dir.getEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
}
catch (FileNotFoundException ex)
{
/*
* A missing document summary information stream is not an error
* and therefore silently ignored here.
*/
}
/*
* If there is a document summry information stream, read it from
* the POI filesystem.
*/
if (dsiEntry != null)
{
final DocumentInputStream dis = new DocumentInputStream(dsiEntry);
final PropertySet ps = new PropertySet(dis);
final DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps);
final SummaryInformation si = new SummaryInformation(ps);
/* Execute the get... methods. */
System.out.println(si.getAuthor());
As explained in the POI overview at http://poi.apache.org/overview.html there are more types of file parsers.
The following examples extract the Author/Creator from 2003 office files:
public static String parseOLE2FileAuthor(File file) {
String author=null;
try {
FileInputStream stream = new FileInputStream(file);
POIFSFileSystem poifs = new POIFSFileSystem(stream);
DirectoryEntry dir = poifs.getRoot();
DocumentEntry siEntry = (DocumentEntry)dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
DocumentInputStream dis = new DocumentInputStream(siEntry);
PropertySet ps = new PropertySet(dis);
SummaryInformation si = new SummaryInformation(ps);
author=si.getAuthor();
stream.close();
} catch (IOException ex) {
ex.getStackTrace();
} catch (NoPropertySetStreamException ex) {
ex.getStackTrace();
} catch (MarkUnsupportedException ex) {
ex.getStackTrace();
} catch (UnexpectedPropertySetTypeException ex) {
ex.getStackTrace();
}
return author;
}
For docx,pptx,xlsx the POI has specialized classes.
Example for .docx file:
public static String parseDOCX(File file){
String author=null;
FileInputStream stream;
try {
stream = new FileInputStream(file);
XWPFDocument docx = new XWPFDocument(stream);
CoreProperties props = docx.getProperties().getCoreProperties();
author=props.getCreator();
stream.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return author;
}
Use for PPTX use XMLSlideShow or XMLWorkbook instead of XMLDocument.
Please find the sample code here- Appache POI how to
In brief, you can a listener MyPOIFSReaderListener:
SummaryInformation si = (SummaryInformation)
PropertySetFactory.create(event.getStream());
String title = si.getTitle();
String Author= si.getLastAuthor();
......
and register it as :
POIFSReader r = new POIFSReader();
r.registerListener(new MyPOIFSReaderListener(),
"\005SummaryInformation");
r.read(new FileInputStream(filename));
for 2003 office files, you can use classes inherited from POIDocument. here is an example for doc file:
FileInputStream in = new FileInputStream(file);
HWPFDocument doc = new HWPFDocument(in);
author = doc.getSummaryInformation().getAuthor();
and HSLFSlideShowImpl for ppt,
HSSFWorkbook for xls,
HDGFDiagram for vsd.
there are many other file information within the SummaryInformation class.
for 2007 or above office file, see the answer of #Dragos Catalin Trieanu

Read a zip file inside zip file

I have zip file which is inside a folder in zip file please suggest me how to read it using zip input stream.
E.G.:
abc.zip
|
documents/bcd.zip
How to read a zip file inside zip file?
If you want to look through zip files within zip files recursively,
public void lookupSomethingInZip(InputStream fileInputStream) throws IOException {
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream);
String entryName = "";
ZipEntry entry = zipInputStream.getNextEntry();
while (entry!=null) {
entryName = entry.getName();
if (entryName.endsWith("zip")) {
//recur if the entry is a zip file
lookupSomethingInZip(zipInputStream);
}
//do other operation with the entries..
entry=zipInputStream.getNextEntry();
}
}
Call the method with the file input stream derived from the file -
File file = new File(name);
lookupSomethingInZip(new FileInputStream(file));
The following code snippet lists the entries of a ZIP file inside another ZIP file. Adapt it to your needs. ZipFile uses ZipInputStreams underneath the hood.
The code snippet uses Apache Commons IO, specifically IOUtils.copy.
public static void readInnerZipFile(File zipFile, String innerZipFileEntryName) {
ZipFile outerZipFile = null;
File tempFile = null;
FileOutputStream tempOut = null;
ZipFile innerZipFile = null;
try {
outerZipFile = new ZipFile(zipFile);
tempFile = File.createTempFile("tempFile", "zip");
tempOut = new FileOutputStream(tempFile);
IOUtils.copy( //
outerZipFile.getInputStream(new ZipEntry(innerZipFileEntryName)), //
tempOut);
innerZipFile = new ZipFile(tempFile);
Enumeration<? extends ZipEntry> entries = innerZipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
System.out.println(entry);
// InputStream entryIn = innerZipFile.getInputStream(entry);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Make sure to clean up your I/O streams
try {
if (outerZipFile != null)
outerZipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
IOUtils.closeQuietly(tempOut);
if (tempFile != null && !tempFile.delete()) {
System.out.println("Could not delete " + tempFile);
}
try {
if (innerZipFile != null)
innerZipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
readInnerZipFile(new File("abc.zip"), "documents/bcd.zip");
}
Finally got it to work fixing Manas Maji's answer. Minimal solution:
import java.io.*;
import java.nio.file.*;
import java.util.zip.*;
import org.slf4j.*;
public void readZipFileRecursive(final Path zipFile) {
try (final InputStream zipFileStream = Files.newInputStream(zipFile)) {
this.readZipFileStream(zipFileStream);
} catch (IOException e) {
LOG.error("error reading zip file %s!", zipFile, e);
}
}
private void readZipFileStream(final InputStream zipFileStream) {
final ZipInputStream zipInputStream = new ZipInputStream(zipFileStream);
ZipEntry zipEntry;
try {
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
LOG.info("name of zip entry: {}", zipEntry.getName());
if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".zip")) {
this.readZipFileStream(zipInputStream); // recursion
}
}
} catch (IOException e) {
LOG.error("error reading zip file stream", e);
}
}
Care: don't close stream in recursive method.
I have written a code that can unzip all zip files inside a zip file. It can even unzip to n levels of compression. Like for example if you had a zip file inside a zip, inside a zip ( and so on) it would extract all of them. Use the zipFileExtract method of this class and pass the source zip file and destination directory as an argument.
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class RecursiveFileExtract {
private static final int BUFFER_SIZE = 4096;
private static Queue<File> current;
private static List<File> visited;
public static void zipFileExtract(File sourceZipFile, File destinationDirectory) {
Path temp = null;
if(!destinationDirectory.exists())
{
destinationDirectory.mkdirs();
}
try {
temp = Files.move(Paths.get(sourceZipFile.getAbsolutePath()), Paths.get(destinationDirectory.getAbsolutePath()+File.separator+sourceZipFile.getName()));
} catch (IOException e) {
e.printStackTrace();
}
File zipFile = new File(temp.toAbsolutePath().toString());
current = new ConcurrentLinkedQueue<>();
visited = new ArrayList<>();
current.add(zipFile);
do {
unzipCurrent();
zipFinder(destinationDirectory);
}
while (!current.isEmpty());
}
private static void zipFinder(File directory) {
try {
if (directory != null) {
File fileArray[] = directory.listFiles();
if (fileArray != null) {
for (File file : fileArray) {
if (file != null) {
if (file.isDirectory()) {
zipFinder(file);
} else {
if (file.getName().endsWith(".zip")) {
if (!visited.contains(file)) {
current.add(file);
}
}
}
}
}
}
}
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
private static void unzipCurrent() {
try {
while (!current.isEmpty()) {
File file = current.remove();
visited.add(file);
File zipDirectory = new File(file.getParentFile().getAbsolutePath());
unzip(file.getAbsolutePath(), zipDirectory.getAbsolutePath());
}
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
public static void unzip(String zipFilePath, String destDirectory) {
try {
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
Boolean result = dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void extractFile(ZipInputStream zipIn, String filePath) {
try {
File file = new File(filePath);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
Boolean result = parentFile.mkdirs();
if (!result) {
throw new Exception();
}
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
}
}
}

Categories