creating a gz file and adding the tar file into it - java

My task is to tar list of files and this tar should be kept in .gz file. I have succeeded in creating .tar file, but the next step like when creating .gz file I got an issue. After creating .gz file with a tar inside is converted into File format without any extension.
java code to generate .tar file
FileSystem fs = FileSystems.getDefault();
OutputStream tar_output = new FileOutputStream(fs.getPath(hardLink.toString(), tarFileName + ".tar")
.toFile());
ArchiveOutputStream my_tar_ball = new ArchiveStreamFactory().createArchiveOutputStream(
ArchiveStreamFactory.TAR, tar_output);
Path p = null;
TarArchiveEntry tar_file = null;
for (String list : certFileList) {
p = fs.getPath(hardLink.toString(), list);
tar_file = new TarArchiveEntry(p.getFileName().toString());
tar_file.setSize(p.toFile().length());
my_tar_ball.putArchiveEntry(tar_file);
IOUtils.copy(new FileInputStream(p.toFile()), my_tar_ball);
my_tar_ball.closeArchiveEntry();
}
call gzipIt function
gzipIt(hardLink.toString() + "/" + tarFileName + ".gz", hardLink.toString() + "/" + tarFileName + ".tar");
Java code to generate .gz file
public static void gzipIt(String outputDir, String sourceFile) {
byte[] buffer = new byte[1024];
try {
FileOutputStream fos = new FileOutputStream(new File(outputDir));
GZIPOutputStream gzos = new GZIPOutputStream(fos);
FileInputStream in = new FileInputStream(sourceFile);
int len;
while ((len = in.read(buffer)) > 0) {
gzos.write(buffer, 0, len);
}
in.close();
gzos.finish();
gzos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Could anyone help me in resolving the issue.
Regards
Sai

Related

getting error while unzipping

My UnZip class does not unzip whole the file. This class is called from another activity. My zip file is saved in the main directory of the phone's internal storage. The zip file has folders and some video.
What's wrong with this unzip?
What and how should I read file from zip' decompress and unzip is the same meaning?
Thanks for your help!
public class Unzip {
private static final String INPUT_ZIP_FILE = "sdcard/downloaded_issue.zip";
private static final String OUTPUT_FOLDER = "sdcard/Atlantis/";
public static void main()
{
Unzip unZip = new Unzip();
unZip.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER);
}
/**
* Unzip it
* #param zipFile input zip file
* #param outputFolder zip file output folder
*/
public void unZipIt(String zipFile, String outputFolder){
byte[] buffer = new byte[1024];
try{
//create output directory is not exists
File folder = new File(OUTPUT_FOLDER);
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);
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();
if (ze.isDirectory()) {
ze = zis.getNextEntry();
}
}
zis.closeEntry();
zis.close();
System.out.println("Done");
}catch(IOException ex){
ex.printStackTrace();
}
}
}
I think your 'while' loop is broken; you're only fetching the next entry if that next entry is a directory, while I assume you're probably trying to skip the directories.
Anyway, since you create the folders for all files you encounter, you can just skip the folder entries and write the file entries. The only exception would be the creation of empty folders.
Replacing the while-loop by this code should work:
while(ze!=null){
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : "+ newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
if (ze.isDirectory()) {
// create the folder
newFile.mkdirs();
}
else {
// create the parent folder and write to disk
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();
}
// get the next item
ze = zis.getNextEntry();
}

How to create a .zip file from two .doc file?

I want to write a unit test to test creating .zip file from two .doc files. BU I take an error: Error creating zip file: java.io.FileNotFoundException: D:\file1.txt (The system cannot find the file specified)
My code is here:
#Test
public void testIsZipped() {
String actualValue1 = "D:/file1.txt";
String actualValue2 = "D:/file2.txt";
String zipFile = "D:/file.zip";
String[] srcFiles = { actualValue1, actualValue2 };
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(fos);
for (int i = 0; i < srcFiles.length; i++) {
File srcFile = new File(srcFiles[i]);
FileInputStream fis = new FileInputStream(srcFile);
// begin writing a new ZIP entry, positions the stream to the
// start of the entry data
zos.putNextEntry(new ZipEntry(srcFile.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);
}
String result = zos.toString();
assertEquals("D:/file.zip", result);
}
Can I get name of zip file from zos to test, How to understand to pass the test? Can anybody help me to solve this error? Thank you.
First, are your files created in a previous test method? If yes consider that junit tests do not execute in the order you defined your test methods, have a look at this:
How to run test methods in specific order in JUnit4?
Second, you could add a debugging line:
File srcFile = new File(srcFiles[i]);
System.out.append(srcFile+ ": " + srcFile.exists() + " " + srcFile.canRead());
After you solve the exception you will run into this problem, the test will fail:
String result = zos.toString();
assertEquals("D:/file.zip", result);
zos.toString() will return something like: "java.util.zip.ZipOutputStream#1ae369b7" which will not be equal to "D:/file.zip".
String zipFile = "D:/file.zip";
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
System.out.println(zos.toString());

How to directly download a file from server,without saving it in any folder?

if(!ErmUtil.isNull(listOfActualFilePaths) && listOfActualFilePaths.size()>0){
FileOutputStream fos = new FileOutputStream("/smiles/wrk/attachments/ermWeb/taxation/testing.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
Iterator itrOnFNames = listOfActualFilePaths.iterator();
while (itrOnFNames.hasNext()) {
StringBuffer ActualPath = (StringBuffer) itrOnFNames.next();
addToZipFile(ActualPath.toString(), zos);
}
zos.close();//Closing Both Streams
fos.close();
}
public void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
int index = fileName.lastIndexOf("/");
String fileNameForZip = fileName.substring(index+1);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileNameForZip);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
I am using above code, to save zip-ed file on a specific location. But what i want to do is that, instead of saving that file, it get downloaded directly.
Edit 1
See If I want to download a zip file,then according to above code, on path /smiles/wrk/attachments/ermWeb/taxation/testing.zip it will be saved first,then from that folder, I(server) can send it to client(Computer).
But I don't want to save it on the specified path,Instead of "saving first to folder and then sending to client", I directly want to send it to client.

How to unzip a Zip file which contains Images without dropping any image in android? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am working on unzip the zip file which contains Images only here below my code is given.
public void unZipImages(String zipFile, String outputFolder) {
byte[] buffer = new byte[2048];
try {
// create output directory is not exists
File folder = new File(Environment.getExternalStorageDirectory()
+ "/final_unzip_data/" + AppConstants.ManufacturerCode
+ "/Catalog/" + ""); 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();
if (fileName.contains("\\")) {
fileName = fileName.replace("\\", "/");
}
File newFile = new File(outputFolder + File.separator
+ fileName);
System.out.println("file unzip : " + newFile.getAbsoluteFile());
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(); } }
But I don't know what the error is occurring to unzip the file some images are dropping. I have searched many types of codes for unzip but nothing worked.
This code has solved my problem
private void unzipImage(String zipFile, String extractFolder) {
try {
CreateDir();
int BUFFER = 4096;
File file = new File(zipFile);
ZipFile zip = new ZipFile(file);
String newPath = extractFolder;
new File(newPath).mkdir();
Enumeration zipFileEntries = zip.entries();
// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
currentEntry = currentEntry.replace('\\', '/');
File destFile = new File(newPath, currentEntry);
// destFile = new File(newPath, destFile.getName());
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];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos,
BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
zip.close();
}
} catch (Exception e) {
Log.e("ERROR: ", "" + e.getMessage());
}
}
Just have a look at http://www.lingala.net/zip4j/download.php , this library file is quick and good .
And you have the short explanation of using the library here
FYI : Here is the another references .
And regarding your code , I have also tried this snippet in my project already but it was ignoring small images while unzipping , so i used the above library . Now i could get it re-solved .

Cannot delete zip file after unzipping?

I am facing an unusal issue.I am building a tool which is scheduled to run every 5 mins.
It will pick up the zip files from a particular directory and extract files (depending on the file name) to a destination. I am using zipentry to get each filename in zip file and then extracting as required then I back them (zip files, once I finish all the files in a zip) to a particular directory and then delete the zip file. But sometimes (not always) the zip files do not get deleted. Since I am using fileutils.forcedelete(). I am getting an exception: unable to delete file. So I changed to the code to using fileutils.forcedeleteonexit() still some files remain in the source.
Here is a sample of my code:
sourceFile=new file(zipfile);
zipFile = new ZipFile(sourceFile);
zEnum = (Enumeration<ZipEntry>) zipFile.entries();
for (int a = 0; a < zipFile.size(); a++)
{
ZipEntry zE = zEnum.nextElement();
//Function uses zip4j for extracting. No streams used.
extract(String sourceZipFile, String fileNameToExtract, String outputFolder);
}
//I tried it with finally either
zipFile.close();
//Using fileutils to copy. No streams used.
copyFile(sourceFile, backup);
FileUtils.forceDeleteOnExit(sourceFile);
There are no streams used but I am getting a lock on files sometimes (not always).
What seems to be the bug here? Is it the zip4j extraction that is causing the problem or anything else? I am using zip4j 1.3.1.
I think your problem related with OS file buffers, that sometimes are not flushed when you are trying to delete file.
Did you try to use sourceFile.deleteOnExit() instead FileUtils.forceDeleteOnExit(sourceFile)?
Also you can try to check sourceFile.canWrite before deleting (may be it may helps)
You can also try to use FileInputStream() before deleting:
FileInputStream fi = new FileInputStream(sourceFile);
fi.getFD().sync();
Use apache-commons IO's FileDeleteStrategy. Something like:
FileDeleteStrategy.FORCE.delete(file);
Update:
It should be the way IO is being handled in your application. I have written simple code which copies a zip file to a temporary zip, deflates the temporary zip and after few seconds deletes it. Here you go:
public class ZipTest {
private static String dirPath = "/home/ubuntuuser/Desktop/";
public static void main(String[] args) throws Exception {
File myzip = new File(dirPath + "content.zip");
String tempFileStr = dirPath + "content_temp.zip";
File tempFile = new File(tempFileStr);
String unzipFolderStr = dirPath + "unzip";
copyUsingChannels(myzip, tempFile);
// copyUsingStreams(myzip, tempFile);
unZip(tempFileStr, unzipFolderStr);
Thread.sleep(3000);
tempFile.delete();
}
private static void copyUsingStreams(File myzip, File tempFile)
throws IOException, FileNotFoundException {
byte[] barray = new byte[1024];
if (!tempFile.exists())
{
tempFile.createNewFile();
}
FileOutputStream fos = new FileOutputStream(tempFile);
FileInputStream fis = new FileInputStream(myzip);
int length = 0;
while ((length = fis.read(barray)) != -1)
{
fos.write(barray, 0, length);
}
fis.close();
fos.close();
}
public static void copyUsingChannels(final File srcFile, final File destFile) throws Exception
{
if (!destFile.exists())
{
destFile.createNewFile();
}
FileChannel source = new FileInputStream(srcFile).getChannel();
FileChannel destination = new FileOutputStream(destFile).getChannel();
source.transferTo(0, source.size(), destination);
source.close();
destination.close();
}
private static void unZip(String zipFile, String outputFolder) throws Exception {
byte[] buffer = new byte[1024];
File folder = new File(outputFolder);
if (!folder.exists()) {
folder.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : " + newFile.getAbsoluteFile());
new File(newFile.getParent()).mkdirs();
if (ze.isDirectory())
{
newFile.mkdir();
ze = zis.getNextEntry();
continue;
}
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();
}
}

Categories