Check if any Zip file is present on a given path - java

I want to check whether any Zip file is present on a specified path. If present then I want to extract that file on the same path.
How to check if any Zip file is present on a given path?

You can try this code which checks the extension of the file inside the directory and prints the filename if Zip file is present.
public static void main(String[] args)
{
// Directory path here
String path = ".";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".rar") || files.endsWith(".zip"))
{
System.out.println(files);
}
}
}
}
Instead of that If you want to use FilenameFilter as told by Andrew Thompson.
You can implement FilenameFilter in your class.
More help is given on this link.
By this you dont need to check the extension of file .
It will give you only those files which extension is being passed as a parameter.
To extract the zip file if found you can take help of the ZipInputStream package .
You can have a look here to extract the folder.

How to check if Any Zip file is present on a given path?
See File.exists()

This unzips all files in a directory, but it's easy to modify to only unzip a specific file.
package com.wedgeless.stackoverflow;
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Unzips all zip files in a directory
* #author mk
*/
public final class Unzipper
{
public static final String DOT_ZIP = ".ZIP";
public static final FilenameFilter DOT_ZIP_FILTER = new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.toUpperCase().endsWith(DOT_ZIP);
}
};
public static void main(String[] args)
{
File dir = new File("/path/to/dir");
Unzipper unzipper = new Unzipper();
unzipper.unzipDir(dir);
}
public void unzipDir(File dir)
{
for (File file : dir.listFiles(DOT_ZIP_FILTER))
{
unzip(file);
}
}
protected void unzip(File file)
{
File dir = getZipDir(file);
try
{
dir.mkdirs();
ZipFile zip = new ZipFile(file);
Enumeration<? extends ZipEntry> zipEntries = zip.entries();
while (zipEntries.hasMoreElements())
{
ZipEntry zipEntry = zipEntries.nextElement();
File outputFile = new File(dir, zipEntry.getName());
outputFile.getParentFile().mkdirs();
if (!zipEntry.isDirectory())
{
write(zip, zipEntry, outputFile);
}
}
}
catch (IOException e)
{
dir.delete();
}
}
protected void write(ZipFile zip, ZipEntry zipEntry, File outputFile)
throws IOException
{
final BufferedInputStream input = new BufferedInputStream(zip.getInputStream(zipEntry));
final int buffsize = 1024;
final byte buffer[] = new byte[buffsize];
final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(outputFile), buffsize);
try
{
while (input.available() > 0)
{
input.read(buffer, 0, buffsize);
output.write(buffer, 0, buffsize);
}
}
finally
{
output.flush();
output.close();
input.close();
}
}
protected File getZipDir(File zip)
{
File dir = zip.getParentFile();
int index = zip.getName().toUpperCase().lastIndexOf(DOT_ZIP);
String zipPath = zip.getName().substring(0, index);
File zipDir = new File(dir, zipPath);
return zipDir;
}
}
It's also not puzzled when on those rare occasions you get zip files with a extension in a non-standard case e.g. file.ZIP
edit: I guess I should have read the question more carefully. You only asked how to identify if a zip file existed on a path, not how to extract it. Just use the FilenameFilter approach... if you get any hits return true, otherwise false.

Take a File variable and go through all the files inside the director and ckeck for a .zip or .tar.gz or .rar
How to iterate over the files of a certain directory, in Java?

The best way to test the availability of any resource that you want to use is just to try to use it. Any other technique is vulnerable to timing-window problems, critique that you are trying to predict the future, double coding, etc. etc. etc. Just catch the FileNotFoundException that happens when you try to open it. You have to catch it anyway, why write the same code twice?

Related

unable to unzip the zip file on linux environment

I am stuck in this issue very badly. I was trying to unzip the zip file using java. I need to upload a zip file using jsp. In controller it accepts Multipart file. Then I have to unzip this file to some location say a temp directory. I did mulipartFile.transferTo('temp zipfile location'), to place a zip file. Under this location zip file will always be replaced. This (zipcopy) would be the source of zip file to be unziped later.. below is code snippet..
String zipcopy = env.getProperty("zipFileCopier");
file.transferTo(new File(zipcopy));
file is of type Multipart.
This is running well on windows environment. No issues at all. I changed the path in application.properties for Linux environment. What I found is -- it is just NOT creating any unziped directories in temp directory. I call unzip code here :
unziputility.unzip(zipcopy, destTemp);
File extractedDir = new File(destTemp+File.separator+multipartFileName+File.separator+"local");
if(extractedDir!=null && extractedDir.exists() && extractedDir.isDirectory()) {
System.out.println("TEST");
//business logic
}
TEST is not getting printed in Linux env. Also note that above code is in try catch block with ex.printstackTrace method used. However no exception is seen caught. Here is my UnzipUtility class:
UnzipUtility
package abc.xyz.re.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.springframework.stereotype.Component;
#Component
public class UnzipUtility {
private static final int BUFFER_SIZE = 9096;
public void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String entryName = entry.getName();
String filePath = destDirectory + File.separator + entryName;
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdirs();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
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();
}
}
above UnzipUtility when replaced with lingala zip4j..same issue. https://github.com/srikanth-lingala/zip4j.
application.properties
uploadDestTemp = /opt/temp
destDirectory = /opt/apache-tomcat-7.0.39/webapps/ROOT/root_/contents/crbt_tones
zipFileCopier = /opt/zip_download/zipfile.zip
in above application.properties file, uploadDestTemp is already created. Also zipFileCopier directory with zipfile.zip file is created
I re-tested this case by making sample code only for unziping the zip file from one location to other. Again it ran perfect in Windows. But failed in Linux. code below:
package package123;
public class Test4 {
public static void main(String[] args) {
System.out.println("testing...");
try {
UnzipUtility unzipUtility = new UnzipUtility();
String unzipLocation = "/opt/temp";
String zipFilePath = "/opt/zip_download/zipfile.zip";
unzipUtility.unzip(zipFilePath, unzipLocation);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
someone please help me to resolve this issue. kindly tell me why I am not able to use this code on my production Linux environment.

Java File exists Case sensitive .jpg and .JPG

I use this function to detect if my file exists or not. While I have some image stored as .jpg, .JPG, .png, and .PNG. But it always return .jpg or .png as true even if the real file has extension .JPG or .PNG.
After I render it to my webpage it throws an error "Failed to load resource: the server responded with a status of 404 (Not Found)".
public static String getPhotoFileExtension(int empKey){
try{
String[] types = {".jpg",".JPG",".png", ".PNG"};
for(String t : types)
{
String path = "/"+Common.PHOTO_PATH + empKey + t;
File f = new File(Sessions.getCurrent().getWebApp()
.getRealPath(path));
if(f.isFile())
return t;
}
}catch (Exception e) {
e.printStackTrace();
}
return "";
}
So you want to get the real case sensitive names of files stored in your filesystem. Lets imaging we have the following paths:
on Linux: using ext4 (which is case sensitive) /testFolder/test.PnG
on Windows using NTFS (which is not case sensitive) c:\testFolder\test.PnG
Now lets create some Java File Objects to each Image File.
// on Linux
File f1 = new File("/testFolder/test.png");
File f2 = new File("/testFolder/test.PNG");
File f3 = new File("/testFolder/test.PnG");
f1.exists(); // false
f2.exists(); // false
f3.exists(); // true
// on Windows
File f1 = new File("c:\\testFolder\\test.png");
File f2 = new File("c:\\testFolder\\test.PNG");
File f3 = new File("c:\\testFolder\\test.PnG");
f1.exists(); // true
f2.exists(); // true
f3.exists(); // true
Your problem is that all calls of File like File.exists are redirected to the java.io.FileSystem class that represents real Operating System calls of your File System by the JVM. So you cannot distinguish on Windows Machines between test.PNG and test.png. Neither do Windows itself.
But even on Windows each File has a defined name in the File System that could be for example: test.PnG. You will see this in your Windows Explorer or in Command Line if you type dir c:\testFolder.
So what you can do in Java is use the File.list method on the parent directory that results in the Operating System list call for all files in this directory with their real names.
File dir = new File("c://testFolder//");
for(String fileName : dir.list())
System.out.println(fileName);
// OUTPUT: test.PnG
or if you prefer File Objects
File dir = new File("c://testFolder//");
for(File file : dir.listFiles())
System.out.println(file.getName());
// OUTPUT: test.PnG
You can use this to write your own exists Method that is case sensitive on all operating systems
public boolean exists(File dir, String filename){
String[] files = dir.list();
for(String file : files)
if(file.equals(filename))
return true;
return false;
}
Use it like this:
File dir = new File("c:\\testFolder\\");
exists(dir, "test.png"); // false
exists(dir, "test.PNG"); // false
exists(dir, "test.PnG"); // true
EDIT: I have to admit that I was wrong. There is a way to get the real name of a File. I always overlooked the method File.getCanonicalPath.
Again our example: We have that File c:\testFolder\test.PnG.
File f = new File("c://testFolder//test.png");
System.out.println(f.getCanonicalPath());
// OUTPUT: C:\testFolder\test.PnG
With that knowledge you can write a simple test method for the case sensitive extension without iterating all files.
public boolean checkExtensionCaseSensitive(File _file, String _extension) throws IOException{
String canonicalPath = _file.getCanonicalPath();
String extension = "";
int i = canonicalPath.lastIndexOf('.');
if (i > 0) {
extension = canonicalPath.substring(i+1);
if(extension.equals(_extension))
return true;
}
return false;
}
Use it like this:
File f = new File("c://testFolder//test.png");
checkExtensionCaseSensitive(f, "png"); // false
checkExtensionCaseSensitive(f, "PNG"); // false
checkExtensionCaseSensitive(f, "PnG"); // true
If you are looking for a function that in any platform can determine existence of a file and is case-sensitive; this should do it :
public static boolean fileExistsCaseSensitive(String path) {
try {
File file = new File(path);
return file.exists() && file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}
I started messing around a little with this because I haven't used Apache's IOFileFilter before and thought that I would add this solution as a chance to play with it a little.
Here is the code:
import java.io.File;
import java.util.Collection;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
public class CaseInsensitiveFileFinder {
/**
* Attempts to find a file with the given <code>fileName</code> (irrespective of case) in the given
* <code>absoluteDirPath</code>. Note that while this method is able to find <code>fileName</code> ignoring case, it
* may not be able to do so if <code>absoluteDirPath</code> is in an incorrect case - that behavior is OS dependent.
*
* #param absoluteDirPath the absolute path of the parent directory of <code>fileName</code> (e.g. "/Users/me/foo")
* #param fileName the name of the file including extension that may or may not be the correct case
* (e.g. myfile.txt)
* #return an optional reference to the file if found, {#link Optional#empty()} will be returned if the file is not
* found
*/
public Optional<File> findFileIgnoreCase(String absoluteDirPath, final String fileName) {
File directory = new File(absoluteDirPath);
if (!directory.isDirectory()) {
throw new IllegalArgumentException("Directory '" + absoluteDirPath + "' isn't a directory.");
}
IOFileFilter caseInsensitiveFileNameFilter = new IOFileFilter() {
#Override
public boolean accept(File dir, String name) {
boolean isSameFile = fileName.equalsIgnoreCase(name);
return isSameFile;
}
#Override
public boolean accept(File file) {
String name = file.getName();
boolean isSameFile = fileName.equalsIgnoreCase(name);
return isSameFile;
}
};
Collection<File> foundFiles = FileUtils.listFiles(directory, caseInsensitiveFileNameFilter, null);
if (foundFiles == null || foundFiles.isEmpty()) {
return Optional.empty();
}
if (foundFiles.size() > 1) {
throw new IllegalStateException(
"More requirements needed to determine what to do with more than one file. Pick the closest match maybe?");
}
// else exactly one file
File foundFile = foundFiles.iterator().next();
return Optional.of(foundFile);
}
}
And here are some test cases:
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.io.Files;
/**
* Non-quite-unit tests for {#link CaseInsensitiveFileFinder} class.
*/
public class CaseInsensitiveFileFinderTest {
private static String APPENDABLE_NEW_TMP_DIR_PATH;
/**
* Create the files with different cases.
* #throws IOException
*/
#BeforeClass
public static void setup() throws IOException {
File newTmpDir = Files.createTempDir();
String newTmpDirPath = newTmpDir.getCanonicalPath();
final String appendableNewTmpDirPath;
String fileSeparator = System.getProperty("file.separator");
if (!newTmpDirPath.endsWith(fileSeparator)) {
appendableNewTmpDirPath = newTmpDirPath + fileSeparator;
}
else {
appendableNewTmpDirPath = newTmpDirPath;
}
CaseInsensitiveFileFinderTest.APPENDABLE_NEW_TMP_DIR_PATH = appendableNewTmpDirPath;
File foofileDotPng = new File(appendableNewTmpDirPath + "FOOFILE.PNG");
Files.touch(foofileDotPng);
assertTrue(foofileDotPng.isFile());
File barfileDotJpg = new File(appendableNewTmpDirPath + "BARFILE.JPG");
Files.touch(barfileDotJpg);
assertTrue(barfileDotJpg.isFile());
}
#AfterClass
public static void teardown() throws IOException {
File newTmpDir = new File(CaseInsensitiveFileFinderTest.APPENDABLE_NEW_TMP_DIR_PATH);
assertTrue(newTmpDir.isDirectory());
// delete even though directory isn't empty
FileUtils.deleteDirectory(newTmpDir);
}
#Test
public void findFooFilePngUsingLowercase() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "foofile.png");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "FOOFILE.PNG", foundFile.getCanonicalPath());
}
#Test
public void findBarFileJpgUsingLowercase() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "barfile.jpg");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "BARFILE.JPG", foundFile.getCanonicalPath());
}
#Test
public void findFileThatDoesNotExist() {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(APPENDABLE_NEW_TMP_DIR_PATH, "dne.txt");
assertFalse(optFoundFile.isPresent());
}
#Test
public void findFooFileUsingDirWithNoTrailingFileSeparator() throws IOException {
CaseInsensitiveFileFinder fileFinder = new CaseInsensitiveFileFinder();
String newDirPathWithNoTrailingFileSep = StringUtils.chop(APPENDABLE_NEW_TMP_DIR_PATH);
Optional<File> optFoundFile = fileFinder.findFileIgnoreCase(newDirPathWithNoTrailingFileSep, "FOOFILE.PNG");
assertTrue(optFoundFile.isPresent());
File foundFile = optFoundFile.get();
assertTrue(foundFile.isFile());
assertEquals(APPENDABLE_NEW_TMP_DIR_PATH + "FOOFILE.PNG", foundFile.getCanonicalPath());
}
}
Hope that helps.
Instead of returning t (the file extension) return the file Object. That way your certain that you have the correct file. If you don't want to return the file object return the file name with the extension.
public static File getPhotoFileExtension(int empKey){
try{
String[] types = {".jpg",".JPG",".png", ".PNG"};
for(String t : types)
{
String path = "/"+Common.PHOTO_PATH + empKey + t;
File f = new File(Sessions.getCurrent().getWebApp()
.getRealPath(path));
if(f.isFile())
return f;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
With that NiMa Thr said, you can do what you are looking for with this code :
On Windows, if the file exists, with any case, it will return true. If the file doesn't exists, the canonical name will be the same, so it will return false.
On Linux, if the file exists with a different case, the canonical name will return this different name, and the method will return true.
public static boolean fileExistsCaseInsensitive(String path) {
try {
File file = new File(path);
return file.exists() || !file.getCanonicalFile().getName().equals(file.getName());
} catch (IOException e) {
return false;
}
}

How to zip only .txt files using java

package codes;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Rough {
public static void main(String[] args) throws IOException {
private static final String FOLDER_PATH = "C:\\Users\\s13w63\\Desktop\\Zip";
File dir = new File(FOLDER_PATH);
File[] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File directory, String fileName) {
if (fileName.endsWith(".txt")) {
return true;
}
return false;
}
});
for (File f : files)
{
FileOutputStream fos=new FileOutputStream("C:\\Users\\s13w63\\Desktop\\Source.zip");
ZipOutputStream zos=new ZipOutputStream(fos);
ZipEntry ze=new ZipEntry(f.getCanonicalPath());
zos.putNextEntry(ze);
zos.close();
System.out.println(f.getCanonicalPath());
}
}
}
I tried this code to ZIP the files, it was showing the file names but not zipping them. Should I have to add anything..and it was showing there is error in code continue to compile??
Help me to solve this issue
Use java.nio.file; it has a very nice solution to your problem.
Illustration:
final Path zipPath = Paths.get("C:\\Users\\s13w63\\Desktop\\Source.zip");
final Path dir = Paths.get("C:\\Users\\s13w63\\Desktop\\Zip");
final DirectoryStream<Path> dirstream
= Files.newDirectoryStream(dir, "*.txt");
final URI uri = URI.create("jar:" + zipPath.toUri());
final Map<String, ?> env = Collections.emptyMap();
String filename;
try (
final FileSystem zipfs = FileSystems.newFileSystem(uri, env);
) {
for (final Path entry: dirstream) {
filename = dir.relativize(entry).toString();
Files.copy(entry, zipfs.getPath("/" + filename));
}
}
Yes, that's right, you can open a zip file as a FileSystem; as such, every operation in Files can be used "on a zip"!
This is JSR 203 for you; you even have FileSystem implementations in memory, over FTP, Dropbox, and others.
Note about the necessity to have the file name as a String: it is because you cannot .resolve() a Path against another if the other Path is from a different provider; I have published a package which solves this particular problem (among others) and has a MorePaths.resolve() method for such cases.
Bharat,
Please paste the error message that you see
Also, I see few issues with your approach.
You might need to do the below things
Take out the definition of FOS and ZOS from the for loop and move it above it...
The code to add the file is missing...
Move zos.close() after the for loop
You could use the below code to add contents of the text file to the ZipOutputStream
/**
* Adds a file to the current zip output stream
*
* #param file
* the file to be added
* #param zos
* the current zip output stream
*/
private static void addFileToZip(File file, ZipOutputStream zos) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
zos.putNextEntry(new ZipEntry(file.getName()));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = bis.read(bytesIn)) != -1) {
zos.write(bytesIn, 0, read);
}
zos.closeEntry();
} catch (IOException e) {
//Take appropriate action
}
}

Failed to move file to another directory using renameTo

import java.io.File;
import org.apache.commons.io.FilenameUtils;
public class Tester {
public static void main(String[] args) {
String rootPath = "F:\\Java\\Java_Project";
File fRoot = new File(rootPath);
File[] fsSub = fRoot.listFiles();
for (File file : fsSub) {
if(file.isDirectory()) continue;
String fileNewPath = FilenameUtils.removeExtension(file.getPath()) + "\\" + file.getName();
File fNew = new File(fileNewPath);
try {
file.renameTo(fNew);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to move the file to another directory,for instance,if the File path is
"C:\out.txt"
than I want to move to
"C:\out\out.txt"
If i try to print the original File and the new original information, the work well,But they just can not move successful.
I suggest to try Java 7 NIO2
Files.move(Path source, Path target, CopyOption... options)

How to unzip a zip folder containing different file formats using Java

I need to unzip a zipped directory containing different files' format like .txt, .xml, .xls etc.
I am able to unzip if the directory contains only .txt files but it fails with other files format. Below is the program that I am using and after a bit of googling, all I saw was similar approach -
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUtils {
public static void extractFile(InputStream inStream, OutputStream outStream) throws IOException {
byte[] buf = new byte[1024];
int l;
while ((l = inStream.read(buf)) >= 0) {
outStream.write(buf, 0, l);
}
inStream.close();
outStream.close();
}
public static void main(String[] args) {
Enumeration enumEntries;
ZipFile zip;
try {
zip = new ZipFile("myzip.zip");
enumEntries = zip.entries();
while (enumEntries.hasMoreElements()) {
ZipEntry zipentry = (ZipEntry) enumEntries.nextElement();
if (zipentry.isDirectory()) {
System.out.println("Name of Extract directory : " + zipentry.getName());
(new File(zipentry.getName())).mkdir();
continue;
}
System.out.println("Name of Extract fille : " + zipentry.getName());
extractFile(zip.getInputStream(zipentry), new FileOutputStream(zipentry.getName()));
}
zip.close();
} catch (IOException ioe) {
System.out.println("There is an IoException Occured :" + ioe);
ioe.printStackTrace();
}
}
}
Throws the below exception -
There is an IoException Occured :java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
java.io.FileNotFoundException: myzip\abc.xml (The system cannot find the path specified)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
at java.io.FileOutputStream.<init>(FileOutputStream.java:104)
at updaterunresults.ZipUtils.main(ZipUtils.java:43)
When you try to open the file that is going to contain the extracted content, the error occurs.
This is because the myzip folder is not available.
So check if it indeed is not available and create it before extracting the zip:
File outputDirectory = new File("myzip");
if(!outputDirectory.exists()){
outputDirectory.mkdir();
}
As #Perception pointed out in the comments: The output location is relative to the active/working directory. This is probably not very convenient, so you might want to add the extraction location to the location of the extracted files:
File outputLocation = new File(outputDirectory, zipentry.getName());
extractFile(zip.getInputStream(zipentry), new FileOutputStream(outputLocation));
(of course you need also add outputLocation to the directory creation code)
This is a good example in which he showed to unzip all the formats (pdf, txt etc) have look its quite
or you can use this code might work (i haven't tried this)
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipUtils
{
private static final int BUFFER_SIZE = 4096;
private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException
{
byte[] buffer = new byte[BUFFER_SIZE];
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir,name)));
int count = -1;
while ((count = in.read(buffer)) != -1)
out.write(buffer, 0, count);
out.close();
}
private static void mkdirs(File outdir,String path)
{
File d = new File(outdir, path);
if( !d.exists() )
d.mkdirs();
}
private static String dirpart(String name)
{
int s = name.lastIndexOf( File.separatorChar );
return s == -1 ? null : name.substring( 0, s );
}
/***
* Extract zipfile to outdir with complete directory structure
* #param zipfile Input .zip file
* #param outdir Output directory
*/
public static void extract(File zipfile, File outdir)
{
try
{
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile));
ZipEntry entry;
String name, dir;
while ((entry = zin.getNextEntry()) != null)
{
name = entry.getName();
if( entry.isDirectory() )
{
mkdirs(outdir,name);
continue;
}
/* this part is necessary because file entry can come before
* directory entry where is file located
* i.e.:
* /foo/foo.txt
* /foo/
*/
dir = dirpart(name);
if( dir != null )
mkdirs(outdir,dir);
extractFile(zin, outdir, name);
}
zin.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Regards

Categories

Resources