getting issue in unzipping folders - files from folder to folder - java

below is my method for unzipping folder to destination folder and method definition
unzip(filepath, unzipLocation);
here is my method to unzip a zip file this method works file but getting problem when my zip file comes like a.zip which have folder 2 folder (i.e abc1,abc2) and again folder abc1 have folder and it have files please help me
private void unzip(String src, String dest) {
String _location = "";
final int BUFFER_SIZE = 4096;
_location = dest;
System.out.println("_location ::: " + dest + "");
System.out.println("src ::: " + src + "");
BufferedOutputStream bufferedOutputStream = null;
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(src);
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String zipEntryName = zipEntry.getName();
String name = dest.substring(dest.lastIndexOf("/") - 1);
// System.out.println("NAME "+name);
// File FileName = new File(FolderName);
File FileName = new File(_location.toString());
if (!FileName.isDirectory()) {
try {
if (FileName.mkdir()) {
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
String loc = "";
String fname = "";
String LOC = "";
LOC = _location.toString();
// File file = new File(FolderName+"/" +zipEntryName);
System.out.println("ZIP " + zipEntryName + "");
// zipEntryName=zipEntryName.r
if (zipEntryName.contains("/")) {
String[] file = zipEntryName.split("/");
System.out.println("CHECK ::: " + file.length);
System.out.println("CHECK ::: " + file[0] + "");
String test = zipEntryName.substring(zipEntryName.lastIndexOf("/"), zipEntryName.length());
System.out.println("TEST " + test + "");
if (test.length() > 1) {
LOC = "";
// zipEntryName = file[1];
zipEntryName = file[file.length - 1];
System.out.println("ZIP UPDATED " + zipEntryName + "");
// _location=_location+"/"+file[0]+"/";
String l = "";
for (int i = 0; i < file.length - 1; i++) {
l = l + "/" + file[i];
}
// System.out.println("TESTTTTTTTT " + l + "");
// loc = _location + "/" + file[0];
// loc = _location + "/" + l;
LOC = _location + "/" + l;
File thumb = new File(LOC);
if (!thumb.exists()) {
thumb.mkdir();
}
System.out.println("createddd dir ");
System.out.println("createddd dir loc " + loc);
} else {
System.out.println("create dir ");
System.out.println("HERE _location111: : : : " + _location);
System.out.println("HERE zipEntryName1111 : : : : /" + zipEntryName);
// File thumb = new File(_location+"/"+zipEntryName);
File thumb = new File(LOC + "/" + zipEntryName);
if (!thumb.exists()) {
thumb.mkdir();
}
}
}
System.out.println("HERE _location: : : : " + _location);
System.out.println("HERE zipEntryName : : : : /" + zipEntryName);
System.out.println("HERE loc : : : : /" + loc);
// File file = new File(_location + "/" + zipEntryName);
File file = new File(LOC + "/" + zipEntryName);
if (file.exists()) {
} else {
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte buffer[] = new byte[BUFFER_SIZE];
FileOutputStream fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, BUFFER_SIZE);
int count;
while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
}
zipInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void unZipIt(String zipFile, String outputFolder) {
byte[] buffer = new byte[1024];
//mm System.out.println("ZIP FILE "+zipFile+"");
//mm System.out.println("outputFolder FILE "+outputFolder+"");
try {
//create output directory is not exists
File folder = new File(outputFolder);
if (!folder.exists()) {
folder.mkdir();
}
//get the zip file content
ZipInputStream zis =
new ZipInputStream(new FileInputStream(zipFile));
//get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
//mm System.out.println("file unzip : " + newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}

Related

Unzipping in java, every file unzips except for one

I am building a library for android, and it requires me to unzip files. It works on every single other file except for one file in one particular archive. I get a file not found exception on this. I am not a java expert, or an android expert, but my team is also stumped. Just hoping someone can spot something in my code that could be creating a bug.
public static void unzip(File zipFile,
String unzipFilePath,
FetchInterface responseHandler,
JSONObject json) {
final int BUFFER_SIZE = 4096;
String filename;
InputStream inputStream;
ZipInputStream zipInputStream;
ZipEntry zipEntry = null;
String path = unzipFilePath + File.separator;
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
String zipRootDirectory = null;
inputStream = new FileInputStream(zipFile);
zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
byte[] buffer = new byte[BUFFER_SIZE];
int count;
// Log.d(tag, zipFile.getName());
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
filename = zipEntry.getName();
Log.d(tag, "ZIP ENTRY: " + zipEntry.getName());
if (zipRootDirectory == null) {
zipRootDirectory = zipEntry.getName().split("\\/")[0];
// Log.d(tag, "ROOT DIR: " + zipRootDirectory);
}
if (zipEntry.isDirectory()) {
Log.d(tag, "ZIPENTRY IS DIR: " + zipEntry.toString());
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
try {
FileOutputStream fout = new FileOutputStream(path + filename);
Log.e(tag, "FILENAME: " + filename);
while ((count = zipInputStream.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
} catch(FileNotFoundException e) {
Log.e(tag, "ERROR AT THIS FILE: " + filename);
e.printStackTrace();
}
zipInputStream.closeEntry();
}
zipInputStream.close();
File zipRootDirectoryFile = new File(path + File.separator + zipRootDirectory);
if (zipRootDirectoryFile.exists()) {
Log.d(tag, zipRootDirectoryFile.getName());
File renameFile = new File(path + File.separator + "html" + File.separator);
zipRootDirectoryFile.renameTo(renameFile);
} else {
Log.e(tag, "directory cannot be renamed as it does not exist");
}
} catch (IOException e) {
e.getStackTrace();
}
}

multi-pag tif to several jpeg files (java)

Hello I was able to convert a tif file to jpeg with the following code that I got from
https://stackoverflow.com/questions/15429011/how-to-convert-tiff-to-jpeg-png-in-java#=
String inPath = "./tifTest/113873996.002.tif";
String otPath = "./tifTest/113873996.002-0.jpeg";
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(inPath), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(new FileOutputStream(otPath), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TifToJpeg.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TifToJpeg.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This only works with one-page tif file, and when I use it with a multi-page tif, it only saves the first page.
How can I modified this to save a mymultipagetif.tif into:
mymultipagetif-0.jpeg
mymultipagetif-1.jpeg
mymultipagetif-2.jpeg
Thanks!
This will takes a multi-page TIFF file (in the SeekableStream), extract the pages in the pages array ("1", "3", "4" for example) and write them into a single multi-page tiff into the file outTIffFileName. Modify as desired.
private String _ExtractListOfPages (SeekableStream ss, String outTiffFileName, String[] pages){
// pageNums is a String array of 0-based page numbers.
try {
TIFFDirectory td = new TIFFDirectory(ss, 0);
if (debugOn) {
System.out.println("Directory has " + Integer.toString(td.getNumEntries()) + " entries");
System.out.println("Getting TIFFFields");
System.out.println("X resolution = " + Float.toString(td.getFieldAsFloat(TIFFImageDecoder.TIFF_X_RESOLUTION)));
System.out.println("Y resolution = " + Float.toString(td.getFieldAsFloat(TIFFImageDecoder.TIFF_Y_RESOLUTION)));
System.out.println("Resolution unit = " + Long.toString(td.getFieldAsLong(TIFFImageDecoder.TIFF_RESOLUTION_UNIT)));
}
ImageDecoder decodedImage = ImageCodec.createImageDecoder("tiff", ss, null);
int count = decodedImage.getNumPages();
if (debugOn) { System.out.println("Input image has " + count + " page(s)"); }
TIFFEncodeParam param = new TIFFEncodeParam();
TIFFField tf = td.getField(259); // Compression as specified in the input file
param.setCompression(tf.getAsInt(0)); // Set the compression of the output to be the same.
param.setLittleEndian(false); // Intel
param.setExtraFields(td.getFields());
FileOutputStream fOut = new FileOutputStream(outTiffFileName);
Vector<RenderedImage> vector = new Vector<RenderedImage>();
RenderedImage page0 = decodedImage.decodeAsRenderedImage(Integer.parseInt(pages[0]));
BufferedImage img0 = new BufferedImage(page0.getColorModel(), (WritableRaster)page0.getData(), false, null);
int pgNum;
// Adding the extra pages starts with the second one on the list.
for (int i = 1; i < pages.length; i++ ) {
pgNum = Integer.parseInt(pages[i]);
if (debugOn) { System.out.println ("Page number " + pgNum); }
RenderedImage page = decodedImage.decodeAsRenderedImage(pgNum);
if (debugOn) { System.out.println ("Page is " + Integer.toString(page.getWidth()) + " pixels wide and "+ Integer.toString(page.getHeight()) + " pixels high."); }
if (debugOn) { System.out.println("Adding page " + pages[i] + " to vector"); }
vector.add(page);
}
param.setExtraImages(vector.iterator());
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", fOut, param);
if (debugOn) { System.out.println("Encoding page " + pages[0]); }
encoder.encode(decodedImage.decodeAsRenderedImage(Integer.parseInt(pages[0])));
fOut.close();
} catch (Exception e) {
System.out.println(e.toString());
return("Not OK " + e.getMessage());
}
return ("OK");
}

tar.gz decompression failing using apache commons-compress

Hi Guys I am using apache Commons-compress 1.9 to compress and decompress tar.gz file. Now the issue I am facing while decompressing the file. While decompressing it is saying the all the files inside the compressed folder not found. following is the decompressing code
public static boolean uncompressTarGz(String tarFileName, String outputDir, Logger log) throws IOException {
try (TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(tarFileName)))) {
TarArchiveEntry tarEntry = (TarArchiveEntry) tarArchiveInputStream.getNextEntry();
log.info("OutputDir : " + outputDir);
log.info("Tar File Name : " + tarFileName);
Files.createDirectories(Paths.get(outputDir));
while (tarEntry != null) {
log.info("Tarentry : " + tarEntry.getName());
File destPath = new File(outputDir, tarEntry.getName());
log.info("1");
if (!tarEntry.isDirectory()) {
destPath.createNewFile();
log.info("2");
try (FileOutputStream fout = new FileOutputStream(destPath);) {
IOUtils.copy(tarArchiveInputStream, fout);
} catch (Throwable e) {
log.info("Error : " + e + " reason : " + e.getMessage());
}
log.info("3");
// byte[] buffer = new byte[8192];
// int n = 0;
// while (-1 != (n = tarArchiveInputStream.read(buffer))) {
// fout.write(buffer, 0, n);
// }
} else {
destPath.mkdir();
}
tarEntry = (TarArchiveEntry) tarArchiveInputStream.getNextEntry();
}
return true;
} catch (Throwable e) {
log.info("Exception while untar : " + e.getMessage());
return false;
}
}
I getting error as /tmp/customTAR/customfiles/filesSucceeded (No such file or directory).
Can anyone please help me figure out what I might be doing wrong.
Thanks in advance.

zip/compress a folder on android

I used the following code to zip my files and it works great but I would like to zip only the subfolders and not have the root of the tree show up in the zip file.
public boolean zipFileAtPath(String sourcePath, String toLocation) {
// ArrayList<String> contentList = new ArrayList<String>();
File sourceFile = new File(sourcePath);
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
if (sourceFile.isDirectory()) {
zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
byte data[] = new byte[BUFFER];
FileInputStream fi = new FileInputStream(sourcePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void zipSubFolder(ZipOutputStream out, File folder,
int basePathLength) throws IOException {
File[] fileList = folder.listFiles();
BufferedInputStream origin = null;
for (File file : fileList) {
if (file.isDirectory()) {
zipSubFolder(out, file, basePathLength);
} else {
byte data[] = new byte[BUFFER];
String unmodifiedFilePath = file.getPath();
String relativePath = unmodifiedFilePath
.substring(basePathLength);
Log.i("ZIP SUBFOLDER", "Relative Path : " + relativePath);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
}
public String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
Right now if I enter Environment.getExternalStorageDirectory().toString()+"/X123" as the sourcePath X123 is included in the tree.
-ZipFile
-X123
-SubFolder1
-SubFolder2
-...
I would like to remove X123
-ZipFile
-SubFolder1
-SubFolder2
-...
Thank you
Played around and ended up using the following code:
static 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();
}
static 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.replace("X123/", "") + "/" + folder.getName()));
//zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
static 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);
}
}
}

Compressing a folder into a ZipFile

I have this Java method to upload a file. I am trying to cater for users trying to upload a folder by compressing that folder into a zip file and upload it instead. For some reason in my case file.isDirectory() and file.isFile() are not working correctly.. even though the filename does not contain any extension, file.isFile() is returning true and isDirectory() returns false. Also directory.list() is also acting weird by returning null.
What can be the problem? Am I doing something wrong?
public File uploadFile(FileItem item, String filename, int ticket_id) throws IOException
{
FileOutputStream out = null;
InputStream fileContent = null;
File file = null;
try
{
//fullpath returns C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test
StringBuffer fullPath = new StringBuffer();
fullPath.append(Attachment.attachments_path);
fullPath.append("t");
fullPath.append(Integer.toString(ticket_id));
fullPath.append(File.separator);
fullPath.append(filename);
System.out.println("filename " + filename);
file = new File(fullPath.toString());
if (!file.exists())
{
// if directory does not exist, create it
file.getParentFile().mkdirs();
}
if (file.isFile())
{
// if file is not a folder
out = new FileOutputStream(file);
fileContent = item.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
// read all the file and write it to created file
while ((read = fileContent.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
}
else if (file.isDirectory())
{
ZipFile appZip = new ZipFile(fullPath.toString());
appZip.generateFileList(file);
appZip.zipIt(filename + ".zip");
}
}
catch (FileNotFoundException e)
{
LogFile.logError("[FileUpload.uploadFile()] " + e.getMessage());
}
catch (IOException e1)
{
LogFile.logError("[FileUpload.uploadFile()] " + e1.getMessage());
}
finally
{
if (out != null)
{
out.close();
}
if (fileContent != null)
{
fileContent.close();
}
}
return file;
}
This is the ZipFile class I am using
public class ZipFile
{
List<String> fileList = null;
String source_folder = "";
public ZipFile(String source_folder)
{
fileList = new ArrayList<String>();
this.source_folder = source_folder;
}
public void zipIt(String zipFile)
{
byte[] buffer = new byte[1024];
String source = "";
try
{
try
{
source = source_folder.substring(source_folder.lastIndexOf("\\") + 1, source_folder.length());
}
catch(Exception e)
{
source = source_folder;
}
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String file : this.fileList)
{
ZipEntry ze = new ZipEntry(source + File.separator + file);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(source_folder + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
//remember close it
zos.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public void generateFileList(File node)
{
// add file only
if(node.isFile())
{
fileList.add(generateZipEntry(node.toString()));
}
if(node.isDirectory())
{
String[] subNode = node.list();
if (subNode != null) {
for(String filename : subNode)
{
generateFileList(new File (node, filename));
}
}
}
}
private String generateZipEntry(String path)
{
return path.substring(source_folder.length() + 1, path.length());
}
}
file.list() is being done in the generateFileList method in ZipFile class. I know this is returning null since I tried detecting whether the file is a folder or a file by using filename.indexOf(".") instead of isDirectory() and isFile() since they were not working. But I wish I had an explanation for this.
Thanks for your help!
if (!file.exists()) {
// if directory does not exist, create it
file.mkdirs();
}
will create directory and test file.isDirectory() will return true
It could be a problem with the path?
C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test
You are mixing backslash with slash...
I tested your code block
ZipFile appZip = new ZipFile(file.toString());
appZip.generateFileList(file);
appZip.zipIt(filename + ".zip");
with a local folder and it's working perfectly. I think you are passing a invalid path. This may be the cause isFile or isDirectory methods are acting strangely. Try to add a validation statement at the starting of generateFileList method using File API:
if(!node.exists) {
// return some flag to signify error OR throw a suitable Exception
}
This should work.
public String compressData(String srcDir) {
String zipFile = srcDir+".zip";
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File dir = new File(srcDir);
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Adding file: " + files[i].getName());
FileInputStream fis = new FileInputStream(files[i]);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}
catch (IOException ioe) {
System.out.println("Error creating zip file" + ioe);
}
return zipFile;
}

Categories