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
Related
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)
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()));
}
}
}
}
I'm writing java coding if file 'id' in sql server table matches filename of file on local directory..how to scan the file and check the filename is match without using for loop.
String pathJ = "C:\\sampleDirectory";
NewsContentObj[] newObj = firstTimeRetrieveRecordFromDB();
for (NewsContentObj temp : newObj) {
File dir = new File("C:\\sampleDirectory");
File[] files = dir.listFiles();
Arrays.sort(files);
for (File file : files){
String path1 = file.getAbsolutePath();
String path = file.getName();
if(temp.getStat().equals(file)){
System.out.println("first path:" + file );
//System.out.println("first path1:" + files[i].getName());
cacheStaticL(pathJ,path);
}
//}
}
}
Thanks
You can use bellow code to check if file exist in given directory
boolean check = new File(directory, temp).exists();
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()).
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