Unzip a file from SDcard - java

I am trying to unzip a file from sdcard using below code
public void unzip(String zipFilePath, String destDirectory, String filename) throws IOException {
File destDir = new File(destDirectory);
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
// iterates over entries in the zip file
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory ;
File dir = new File(filename);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
/**
* Extracts a zip entry (file entry)
* #param zipIn
* #param filePath
* #throws IOException
*/
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();
}
The above code is giving me errors. below are the logs
java.io.FileNotFoundException: /mnt/sdcard/unZipedFiles/myfile/tt/images.jpg: open failed: ENOENT (No such file or directory)
Here I ziped directory which contains images/sub-directory, then I am trying to unzip.
Can anybody tell me the reasons
Thanks

You are trying to write files to a directory that does not exist. This will not work. Not only do you need to create the files when unZIPping, you need to create the directories as well.
Add the following to extractPath() as its opening line:
filePath.getParentFile().mkdirs();
This gets the directory that should contain your desired file (filePath.getParentFile()), then creates all necessary subdirectories to get there (mkdirs()).

Related

Need some help to extract ZIP folder using java code and which that ZIP file contains inside one more zip file, jar files and folders

Need some help to extract ZIP folder which contains inside one more zip file, jar files and folders using java code
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();
// iterates over entries in the zip file
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
System.out.println("filePath:"+filePath);
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory
File dir = new File(filePath);
dir.mkdir();
}
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();
}
I need code for extract outside zip file and inside zip folder using java code.
I was getting fileNotFoundException while executing above code
java.io.FileNotFoundException: C:\siva\Test.zip (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at com.main.UnzipUtility.extractFile(UnzipUtility.java:62)
at com.main.UnzipUtility.unzip(UnzipUtility.java:40)
at com.main.MainClass.main(MainClass.java:14)

Unzip nested jar files java

I am trying to unzip all the jar files and the jar files which is nested in jar file.
For example, let's say there's a Test.jar and inside of the Test.jar, there is Test1.jar,,
What I tried to do is that making a temp directory and unzip them, when it was jar file, recursive call.
Here below is my code and the log I got. I have no idea on that.
I am pretty sure that the input was directory. I have no idea on resolving this error. Also, I am pretty sure that the error is from here (Collection<File> files = FileUtils.listFiles(root, null, recursive);)
Curr directory:/Users/younghoonkwon/jar-analyzer
unzipping directory/Users/younghoonkwon/jar-analyzer/test1.jar#
Curr directory:/Users/younghoonkwon/jar-analyzer/test1.jar#
java.lang.IllegalArgumentException: Parameter 'directory' is not a directory
at org.apache.commons.io.FileUtils.validateListFilesParameters(FileUtils.java:545)
at org.apache.commons.io.FileUtils.listFiles(FileUtils.java:521)
at org.apache.commons.io.FileUtils.listFiles(FileUtils.java:691)
at org.vulnerability.checker.JarParser.unzipJars(JarParser.java:31)
at org.vulnerability.checker.JarParser.unzipJars(JarParser.java:38)
at org.vulnerability.checker.VulnerabilityChecker.main(VulnerabilityChecker.java:26)
[/Users/younghoonkwon/jar-analyzer/test1.jar]
My code:
public void unzipJars(String toFind, String currDirectory) {
File root = new File(currDirectory);
try {
boolean recursive = true;
System.out.println("Curr directory:"+root);
Collection<File> files = FileUtils.listFiles(root, null, recursive);
for (Iterator<File> iterator = files.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
if (file.getName().endsWith(toFind)) {
if(toFind.endsWith("jar")) {
unzip(file.getAbsolutePath() + "#",file.getAbsolutePath());
System.out.println("unzipping directory"+ file.getAbsolutePath()+"#");
unzipJars("jar", file.getAbsolutePath()+"#");
this.jarList.add(file.getAbsolutePath());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
static void unzip(String destDirPath, String zipFilePath) throws IOException {
Runtime.getRuntime().exec("unzip "+ zipFilePath + " -d" + destDirPath);
}
The algorithm seems ok to me. The error seems to be caused by that the unzipped file is not a directory (but a file) or it does not exist. Your unzip() method does not throw any exeption if unzipping the .jar fails because of output file already existing.
Have you been running the code earlier which may have caused that the .jars or directories contain unwanted output files with the same name?
Before the call to FileUtils.listFiles(), check if the root File object is actually a directory and it exists (or if it's a file but not a directory) by File.isDirectory() or File.isFile().
The following method decompress() unzips a JAR file and all the JAR files within it (recursively).
/**
* Size of the buffer to read/write data.
*/
private static final int BUFFER_SIZE = 16384;
/**
* Decompress all JAR files located in a given directory.
*
* #param outputDirectory Path to the directory where the decompressed JAR files are located.
*/
public static void decompress(final String outputDirectory) {
File files = new File(outputDirectory);
for (File f : Objects.requireNonNull(files.listFiles())) {
if (f.getName().endsWith(".jar")) {
try {
JarUtils.decompressDependencyFiles(f.getAbsolutePath());
// delete the original dependency jar file
org.apache.commons.io.FileUtils.forceDelete(f);
} catch (IOException e) {
log.warn("Problem decompressing jar file: " + f.getAbsolutePath());
}
}
}
}
/**
* Decompress all JAR files (recursively).
*
* #param zipFile The file to be decompressed.
*/
private static void decompressDependencyFiles(String zipFile) throws IOException {
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file)) {
String newPath = zipFile.substring(0, zipFile.length() - 4);
new File(newPath).mkdir();
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(newPath, currentEntry);
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte[] data = new byte[BUFFER_SIZE];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
is.close();
}
}
if (currentEntry.endsWith(".jar")) {
// found a zip file, try to open
decompressDependencyFiles(destFile.getAbsolutePath());
FileUtils.forceDelete(new File(destFile.getAbsolutePath()));
}
}
}
}

Unzip file with special character through java.util.zip library

I have my zip file with several files inside it. When I run my unzip code:
public ArrayList<String> unzip(String zipFilePath, String destDirectory, String filename) throws IOException {
ArrayList<String> pathList = new ArrayList<String>();
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
// iterates over entries in the zip file
while (entry != null) {
// Original file name
// String filePath = destDirectory + File.separator + entry.getName();
int _ordPosition = entry.getName().indexOf("_ord");
if (_ordPosition<0)
throw new DatOrderException("Files inside zip file are not in correct format (please order them with _ordXX string)");
String ord = entry.getName().substring(_ordPosition,_ordPosition+6);
String filePath = destDirectory + File.separator + filename + ord + "."+ FilenameUtils.getExtension(entry.getName());
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
pathList.add(filePath);
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
return pathList;
}
if file inside archive contains special character like ยบ I receive exception with Malformed message on row
ZipEntry entry = zipIn.getNextEntry();
Is it possible to rename this file or fix this error? Thanks
Try to read zip file with correct characters encoding - use ZipInputStream(java.io.InputStream, java.nio.charset.Charset) instead of ZipInputStream(java.io.InputStream)
As #Andrew Kolpakov suggested, with
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath),Charset.forName("IBM437"));
it seems to work

Transform zip directory function using java.util.zip to use LZMA

I currently have a function makeBackup() which zips an entire directory into a zip file, the files are however too big so we decided to switch to LZMA.
We found a library which does this (lzma-java) however it seems to compress only a single file, while the zip function we used permits to add files and directories to a zip file.
How can we implement the same with LZMA by changing our function? I added our current function below:
private static void makeBackup()
{
String backupPathString = "/home/backups";
/* zip remote file */
try
{
//name of zip file to create
String zipFilename = "backup.zip";
//create ZipOutputStream object
ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFilename));
//path to the currentFile to be zipped
File zipFolder = new File(backupPathString);
//get path prefix so that the zip file does not contain the whole path
// eg. if currentFile to be zipped is /home/lalit/test
// the zip file when opened will have test currentFile and not home/lalit/test currentFile
int len = zipFolder.getAbsolutePath().lastIndexOf(File.separator);
String baseName = zipFolder.getAbsolutePath().substring(0, len + 1) + File.separator + "todaybackups";
zipFilesInPath(zipOutStream, backupPathString, baseName);
zipOutStream.flush();
zipOutStream.close();
}
catch (IOException e)
{
}
}
private static void zipFilesInPath(ZipOutputStream zipOutputStream, String filePath, String baseName) throws IOException
{
File currentFile = new File(filePath);
ArrayList<File> filesArrayList = new ArrayList<File>(Arrays.asList(currentFile.listFiles()));
if (filesArrayList.isEmpty())
{
String name = currentFile.getAbsolutePath().substring(baseName.length());
ZipEntry zipEntry = new ZipEntry(name + "/" + ".");
zipOutputStream.putNextEntry(zipEntry);
}
for (File file : filesArrayList)
{
if (file.isDirectory())
{
zipFilesInPath(zipOutputStream, file.getAbsolutePath(), baseName);
}
else
{
String name = file.getAbsolutePath().substring(baseName.length());
ZipEntry zipEntry = new ZipEntry(name);
zipOutputStream.putNextEntry(zipEntry);
IOUtils.copy(new FileInputStream(file), zipOutputStream);
zipOutputStream.closeEntry();
}
}
}
private static void unzipFilesToPath(ZipInputStream zipInputStream, String fileExtractPath) throws IOException
{
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null)
{
int count;
byte[] data = new byte[2048];
/*let's make the directory structure needed*/
File destFile = new File(fileExtractPath, entry.getName());
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
if (!entry.isDirectory() && !entry.getName().substring(entry.getName().length() - 1).equals("."))
{
final FileOutputStream fos = new FileOutputStream(fileExtractPath + File.separator + entry.getName());
final BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
while ((count = zipInputStream.read(data, 0, 2048)) != -1)
{
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
}
}
apparently is not possible, and what you have to do is package all your files into a tar/zip and then apply the lzma. take a look at this How to use LZMA SDK to compress/decompress in Java

How to zip multiple files contained in a folder without zipping the entire folder in android?

This is my requirement I have one folder(say: Main folder) which contains three items
One folder and two text files
I want to zip only these three items contained in the Main folder .Right now I am zipping the contents with the Main folder and the resultant zipped folder name is "temp.zip",when I unzip this,I am getting the "Main folder". But my requirement is when I unzip the "temp.zip",it should display only the contents of the Main folder.
Could any one help me in achieving this?
Thank you.
Edit :This is the code I am using to zip the files
This is the code I am zipping the files
public void zipFolder(String srcFolder, String destZipFile)
throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
private void addFolderToZip(String path, String srcFolder,
ZipOutputStream zip) throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/"
+ fileName, zip);
}
}
}
private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
I am calling the zipfolder method with these params :
zipFolder(srcfolder, destipath + "/" + "temp.zip");
Zipping a set of individual files into a single zip in Android should be pretty straight forward. There's a pretty good tutorial here that should get you started:
http://www.jondev.net/articles/Zipping_Files_with_Android_%28Programmatically%29
I just copied from this post
Referred from the matt answer I successfully used this library.
You can try Zip4j, a pure java library to handle zip file. It supports
encryption/decryption of PKWare and AES encryption methods.
http://www.lingala.net/zip4j/
Key features:
Create, Add, Extract, Update, Remove files from a Zip file
Read/Write password protected Zip files
Supports AES 128/256 Encryption
Supports Standard Zip Encryption
Supports Zip64 format
Supports Store (No Compression) and Deflate compression method
Create or extract files from Split Zip files (Ex: z01, z02,...zip)
Supports Unicode file names
Progress Monitor
License:
Zip4j is released under Apache License, Version 2.0
try {
String zipFile = "/locations/data.zip";
String srcFolder = "/locations";
File folder = new File(srcFolder);
String[] sourceFiles = folder.list();
//create byte buffer
byte[] buffer = new byte[1024];
/*
* To create a zip file, use
*
* ZipOutputStream(OutputStream out) constructor of ZipOutputStream
* class.
*/
//create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipFile);
//create object of ZipOutputStream from FileOutputStream
ZipOutputStream zout = new ZipOutputStream(fout);
for (int i = 0; i < sourceFiles.length; i++) {
if (sourceFiles[i].equalsIgnoreCase("file.csv") || sourceFiles[i].equalsIgnoreCase("file1.csv")) {
sourceFiles[i] = srcFolder + fs + sourceFiles[i];
System.out.println("Adding " + sourceFiles[i]);
//create object of FileInputStream for source file
FileInputStream fin = new FileInputStream(sourceFiles[i]);
/*
* To begin writing ZipEntry in the zip file, use
*
* void putNextEntry(ZipEntry entry) method of
* ZipOutputStream class.
*
* This method begins writing a new Zip entry to the zip
* file and positions the stream to the start of the entry
* data.
*/
zout.putNextEntry(new ZipEntry(sourceFiles[i].substring(sourceFiles[i].lastIndexOf("/") + 1)));
/*
* After creating entry in the zip file, actually write the
* file.
*/
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
/*
* After writing the file to ZipOutputStream, use
*
* void closeEntry() method of ZipOutputStream class to
* close the current entry and position the stream to write
* the next entry.
*/
zout.closeEntry();
//close the InputStream
fin.close();
}
}
//close the ZipOutputStream
zout.close();
System.out.println("Zip file has been created!");
} catch (IOException ioe) {
System.out.println("IOException :" + ioe);
}
In windows you can achieve this by the following steps,
1.Open the main folder and select the files which you want to add into zip file
2.Right click -> Add to archieve
3.Choose the archieve format as zip and click 'Ok'

Categories

Resources