I know this question already exists, but I'm not sure how to implement it in my case...
First I created an DataOutuputStream that will write in a file with .uedl extension:
private static DataOutputStream os;
public static final String BASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myApp/logs/"
public static void startReceiveLogs() {
if (debugBaudRate > -1) {
mReadFlag = true;
String time = TimeUtils.getCurrentTime(TimeZone.getDefault());
try {
os = new DataOutputStream(new FileOutputStream(BASE_PATH + time + "_logs.uedl"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mReceiveLogsThread = new Thread(new ReceiveLogsThread());
mReceiveLogsThread.start();
}
}
Here is the writing stuff:
public void run() {
byte[] rbuf = new byte[64];
while (mReadFlag) {
try {
int len = mSerial.readLog(rbuf, mSerialPortLog);
if (len > 0) {
os.write(rbuf, 0, len);
}
} catch (NullPointerException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Once this thread stops running, I'd like to compress that file at the same path.
You try this it will help for you
public boolean zipFileAtPath(String sourcePath, String toLocation) {
final int BUFFER = 2048;
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));
entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
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 {
final int BUFFER = 2048;
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);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
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("/");
if (segments.length == 0)
return "";
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
Related
My Zipped folder contains sub-folder with files but while extracting it, I am not able to achieve the same hierarchy. I'm getting the unzipped structure as follows:-
/storage/emulated/0/unzipped_folder/sub_folder\main.png
/storage/emulated/0/unzipped_folder/sub_folder\test.xml
So while extracting it, I'm not able to get sub_folder as a directory.
I'm using below code while extracting the zip file.
public static void unzip(String zipFile, String location) throws IOException {
try {
File f = new File(location);
if (!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = location + File.separator + ze.getName();
if (ze.isDirectory()) {
File unzipFile = new File(path);
if (!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
} else {
FileOutputStream fout = new FileOutputStream(path, false);
try {
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
} finally {
fout.close();
}
}
}
} finally {
zin.close();
}
} catch (Exception e) {
e.printStackTrace();
Log.e("ZIP STU", "Unzip exception", e);
}
}
Please help, I'm stuck in this for more than 2 days.
Thanks!
Finally I'm able to solve this issue using below code.
public static void unzipEPub(File zipFile, File destinationDir){
ZipFile zip = null;
try {
int DEFUALT_BUFFER = 1024;
destinationDir.mkdirs();
zip = new ZipFile(zipFile);
Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
while (zipFileEntries.hasMoreElements()) {
ZipEntry entry = zipFileEntries.nextElement();
String entryName = entry.getName();
entryName = entryName.replace("\\","/");
File destFile = new File(destinationDir, entryName);
File destinationParent = destFile.getParentFile();
if (destinationParent != null && !destinationParent.exists()) {
destinationParent.mkdirs();
}
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
byte data[] = new byte[DEFUALT_BUFFER];
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest = new BufferedOutputStream(fos, DEFUALT_BUFFER);
while ((currentByte = is.read(data, 0, DEFUALT_BUFFER)) > 0) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (zip != null) {
try {
zip.close();
} catch (IOException ignored) {
}
}
}
}
I'm currently developing an android application in which I've to download a .zip archive and then unzip it. The download of the archive is done correctly. I'm able to unzip it manually directly on the phone or on my computer.
However, when I try to unzip programmatically the archive, I get a UTFDataFormatException. I tried to force the system encoding by adding :
System.setProperty("file.encoding", "UTF-8");
Or to process the names of the files :
filename = new String(ze.getName().getBytes("UTF-8"));
Did I miss something in my unzip function ?
private boolean unzip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[4096];
int count;
while ((ze = zis.getNextEntry()) != null)
{
filename = ze.getName();
if (ze.isDirectory())
{
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
Below the message of the exception :
java.io.UTFDataFormatException: bad byte at 72
After all, I used Zip4j library and it works very well. It's an old library which is not maintained and not callable thanks to gradle, but it fix my problem (http://www.lingala.net/zip4j/).
try
{
ZipFile zipFile = new ZipFile(sourceFile);
zipFile.extractAll(destinationPath);
}
catch (ZipException e)
{
e.printStackTrace();
}
Try this:
public static boolean unzip(String zipFile, String location) {
if (!location.endsWith("/")) {
location += "/";
}
if (!zipFile.endsWith(".zip") || !new File(location + zipFile).exists()) {
return false;
}
int size;
byte[] buffer = new byte[1024];
try {
File f = new File(location);
if (!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(location + zipFile), 1024));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = location + ze.getName();
File unzipFile = new File(path);
if (ze.isDirectory()) {
if (!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
} else {
// check for and create parent directories if they don't exist
File parentDir = unzipFile.getParentFile();
if (null != parentDir) {
if (!parentDir.isDirectory()) {
parentDir.mkdirs();
}
}
// unzip the file
FileOutputStream out = new FileOutputStream(unzipFile, false);
BufferedOutputStream fout = new BufferedOutputStream(out, 1024);
try {
while ((size = zin.read(buffer, 0, 1024)) != -1) {
fout.write(buffer, 0, size);
}
zin.closeEntry();
} finally {
try {
fout.flush();
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} finally {
try {
zin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
Try this,
public class DecompressZip{
private static final int BUFFER_SIZE=8192;
private String _zipFile;
private String _location;
private byte[] _buffer;
/**
* Constructor.
*
* #param zipFile Fully-qualified path to .zip file
* #param location Fully-qualified path to folder where files should be written.
* Path must have a trailing slash.
*/
public DecompressZip(String zipFile, String location)
{
_zipFile = zipFile;
_location = location;
_buffer = new byte[BUFFER_SIZE];
dirChecker("");
}
public void unzip()
{
FileInputStream fin = null;
ZipInputStream zin = null;
OutputStream fout = null;
File outputDir = new File(_location);
File tmp = null;
try {
fin = new FileInputStream(_zipFile);
zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null)
{
Log.d("Decompress", "Unzipping " + ze.getName());
Log.d("Decompress", "FileSize " + ze.getSize());
Log.d("Decompress", "compressedSize " + ze.getCompressedSize());
if (ze.isDirectory())
{
dirChecker(ze.getName());
}
else
{
tmp = File.createTempFile( "decomp", ".tmp", outputDir );
fout = new BufferedOutputStream(new FileOutputStream(tmp));
DownloadFile.copyStream( zin, fout, _buffer, BUFFER_SIZE );
zin.closeEntry();
fout.close();
fout = null;
tmp.renameTo( new File(_location + ze.getName()) );
tmp = null;
}
}
zin.close();
zin = null;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
finally
{
if ( tmp != null ) { try { tmp.delete(); } catch (Exception ignore) {;} }
if ( fout != null ) { try { fout.close(); } catch (Exception ignore) {;} }
if ( zin != null ) { try { zin.closeEntry(); } catch (Exception ignore) {;} }
if ( fin != null ) { try { fin.close(); } catch (Exception ignore) {;} }
}
}
private void dirChecker(String dir)
{
File f = new File(_location + dir);
if (!f.isDirectory())
{
f.mkdirs();
}
}}
try this below code. I have done this to download zipped images.
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class MainActivity extends AppCompatActivity {
private ProgressDialog simpleWaitDialog;
private Bitmap table1,seat1,seat2,seat3,seat4,seat5,dummy;
private ImageView tableIv,seat1Iv,seat2Iv,seat3Iv,seat4Iv,seat5Iv,overlay;
File _zipFile;
InputStream _zipFileStream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableIv=(ImageView)findViewById(R.id.iv);
seat1Iv=(ImageView)findViewById(R.id.seat1IV);
seat2Iv=(ImageView)findViewById(R.id.seat2IV);
seat3Iv=(ImageView)findViewById(R.id.seat3IV);
seat4Iv=(ImageView)findViewById(R.id.seat4IV);
seat5Iv=(ImageView)findViewById(R.id.seat5IV);
overlay=(ImageView)findViewById(R.id.overlayIV);
///data/user/0/com.example.ayyappaboddupalli.zipperunzipper/app_zipper1/themeparts1.zip/dummy/6_player.jpg -location where files stored
ContextWrapper wrapper=new ContextWrapper(this);
File sd = wrapper.getDir("zipper1", MODE_PRIVATE);
File dest = new File(sd, "theme1.zip");
File target = new File(sd, "themeparts1.zip");
if(target.exists())
{
commonCaller(dest,target,sd);
}
else
{
new ImageDownloader().execute();
commonCaller(dest,target,sd);
}
}
private void uriToBitmap(Uri selectedFileUri, String name) {
try {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(selectedFileUri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
assignBitmapToView(image,name);
parcelFileDescriptor.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void assignBitmapToView(Bitmap image, String name) {
String toCompare=name.toString().substring(name.lastIndexOf("/")+1,name.lastIndexOf("."));
switch (toCompare)
{
case "dummy":
dummy=image;
overlay.setImageBitmap(dummy);
break;
case "6_player":
table1=image;
tableIv.setImageBitmap(table1);
break;
case "f1":
seat1=image;
seat1Iv.setImageBitmap(seat1);
break;
case "f2":
seat2=image;
seat2Iv.setImageBitmap(seat2);
break;
case "f3":
seat3=image;
seat3Iv.setImageBitmap(seat3);
break;
case "f4":
seat4=image;
seat4Iv.setImageBitmap(seat4);
break;
case "f5":
seat5=image;
seat5Iv.setImageBitmap(seat5);
break;
}
}
public void commonCaller(File dest,File target,File sd)
{
if(sd.exists()) {
// unzip(dest.getAbsolutePath(), target.getAbsolutePath());
try {
unzipFileIntoDirectory(dest,target);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*public void unzip(String _zipFile, String _targetLocation) {
//create target location folder if not exist
_dirChecker(_zipFile);
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
//create dir if required while unzipping
if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}*/
public void unzip() {
try {
ContextWrapper cws=new ContextWrapper(this);
File sd=cws.getDir("zipper1",MODE_PRIVATE);
File dest=new File(sd,"parts1");
dest.mkdirs();
// final String ROOT_LOCATION = "/sdcard";
Log.i("", "Starting to unzip");
InputStream fin = _zipFileStream;
if(fin == null) {
fin = new FileInputStream(_zipFile);
}
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(dest + "/" + ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(new File(sd.getPath(), ze.getName()));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
// reading and writing
while((count = zin.read(buffer)) != -1)
{
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
zin.closeEntry();
}
}
zin.close();
Log.i("", "Finished unzip");
} catch(Exception e) {
Log.e("", "Unzip Error", e);
}
}
public void unzipFileIntoDirectory(File archive, File destinationDir)
throws Exception {
final int BUFFER_SIZE = 1024;
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream(archive);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
File destFile;
while ((entry = zis.getNextEntry()) != null) {
destFile=new File(destinationDir,entry.getName());
uriToBitmap(Uri.fromFile(destFile),entry.getName());
// destFile = FilesystemUtils.combineFileNames(destinationDir, entry.getName());
if (entry.isDirectory()) {
destFile.mkdirs();
continue;
} else {
int count;
byte data[] = new byte[BUFFER_SIZE];
destFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(destFile);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
fos.close();
}
}
zis.close();
fis.close();
}
private void _dirChecker(String dir) {
File f = new File(dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
private class ImageDownloader extends AsyncTask {
#Override
protected Object doInBackground(Object[] params) {
String url="testing/dummy.zip";
return downloadBitmap(url);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
simpleWaitDialog = new ProgressDialog(MainActivity.this);
simpleWaitDialog.setMessage( "Downloading Image");
simpleWaitDialog.show();
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
simpleWaitDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
downloadImage(url);
return null;
}
}
public void downloadImage(String urlPart) {
URL url = null;
FileDescriptor fd;
try {
int count;
url = new URL(urlPart);
InputStream input = new BufferedInputStream(url.openStream());
ContextWrapper contextWrapper=new ContextWrapper(this);
File sd = contextWrapper.getDir("zipper1", MODE_PRIVATE);
File dest = new File(sd, "theme1.zip");
_zipFileStream=input;
// File file = new File(downloadLocation);
FileOutputStream output = new FileOutputStream(dest); //context.openFileOutput("content.zip", Context.MODE_PRIVATE);
fd = output.getFD();
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_LONG).show();
}
});
//old code
/* ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
String zipString = Base64.encodeToString(response, Base64.DEFAULT);
ContextWrapper contextWrapper=new ContextWrapper(this);
File sd = contextWrapper.getDir("zipper1", MODE_PRIVATE);
File dest = new File(sd, "theme1.zip");
FileOutputStream fos = new FileOutputStream(dest);
fos.write(zipString.getBytes());
fos.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_LONG).show();
}
});*/
}
catch (Exception e) {
e.printStackTrace();
}
}
}
I want to render a pdf which in the raw folder with ParcelFileDescriptor tried too many methods from the other posts but none of them worked for me. Below is the code
I copied the code from the post you suggested and modified my code but still pdf is not opening even its showing no error.
public void render()
{
try
{
imgv = (ImageView) findViewById(R.id.img);
int w = imgv.getWidth();
int h = imgv.getHeight();
Bitmap bm = Bitmap.createBitmap(w,h, Bitmap.Config.ARGB_4444);
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abcd.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abcd.pdf");
// File file = new File("android.resource://com.nyt.ilm.mytestpdfreader/raw/abcd.pdf");
PdfRenderer render = new PdfRenderer(ParcelFileDescriptor.open(file,ParcelFileDescriptor.MODE_READ_ONLY));
if (CurrentPage < 0)
{ CurrentPage =0;
}
else if (CurrentPage > render.getPageCount()){
CurrentPage = render.getPageCount() - 1;
}
Matrix m = imgv.getImageMatrix();
Rect rect = new Rect(0,0,w,h);
render.openPage(CurrentPage).render(bm,rect,m,PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imgv.setImageMatrix(m);
imgv.setImageBitmap(bm);
imgv.invalidate();
}
catch (Exception e)
{
e.printStackTrace();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abcd.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I am able to zip files contained in a particular folder. This is the code that I have used:
public class Compress {
private static final int BUFFER = 2048;
private String[] _files;
private String _zipFile;
public Compress(String[] files, String zipFile) {
_files = files;
_zipFile = zipFile;
}
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for(int i=0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
I'm calling this class in this way in another class:
String[] files = {mainFolderPath+"/text1.txt", mainFolderPath+ "/text2.txt", mainFolderPath +"/NewFolder"};
Compress compress = new Compress(files, sourceFile.getAbsolutePath());
compress.zip();
On running the application I'm getting an IOException.
Could you please tell me how to zip the "NewFolder" which contains another text file along with the text files "text1.txt" and "text2.txt"?
Thank you.
It works for me!!!!!!!! in all my projects I need....
public String[] _files;
public String _zipFile = "/mnt/sdcard/123.zip";
/////zIIIiiiiPPPPPer
public class Compress {
private static final int BUFFER = 2048;
public Compress(String[] files, String zipFile) {
_files = files;
_zipFile = zipFile;
}
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
String path = "/mnt/sdcard/out";
File fileDir = new File( path );
if(!fileDir.exists() || !fileDir.isDirectory())
{
return;
}
String[] _files = fileDir.list();
for ( int i = 0 ; i < _files.length ; i++ )
{
_files[i] = path + "/"+ _files[i];
}
byte data[] = new byte[BUFFER];
for(int i=0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
To call it JuSt do smth like...
Compress cs = new Compress(_files, _zipFile);
I got the solution for my question ie; zipping only the contents of a particular folder which includes a folder along with some text files. This is the code:
public class Compress {
private static final int BUFFER = 2048;
private String[] _files;
private String _zipFile;
public Compress(String[] files, String zipFile) {
_files = files;
_zipFile = zipFile;
}
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(_zipFile);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
String name = _files[i];
File f = new File( _files[i]);
if (f.isDirectory()) {
name = name.endsWith("/") ? name : name + "/";
for (String file : f.list()) {
System.out.println(" checking " + file);
System.out
.println("The folder name is: " + f.getName());
out.putNextEntry(new ZipEntry(f.getName() + "/" + file));
FileInputStream fi = new FileInputStream( _files[i]
+ "/" + file);
origin = new BufferedInputStream(fi, BUFFER);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
System.out.println(" checking folder" + name);
} else {
FileInputStream fi = new FileInputStream( _files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry( _files[i].substring( _files[i]
.lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I need to zip up a "project" folder to allow users to share projects via email. I found a class for zipping up multiple files into one zip, but I need to keep the folder structure in my zip. Is there any way to achieve this on android? Thanks in advance.
This code should do the trick.
Note: you must add file write permissions to your app by adding the WRITE_EXTERNAL_STORAGE permission to your manifest.xml file.
/*
*
* Zips a file at a location and places the resulting zip file at the toLocation
* Example: zipFileAtPath("downloads/myfolder", "downloads/myFolder.zip");
*/
public boolean zipFileAtPath(String sourcePath, String toLocation) {
final int BUFFER = 2048;
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));
entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
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;
}
/*
*
* Zips a subfolder
*
*/
private void zipSubFolder(ZipOutputStream out, File folder,
int basePathLength) throws IOException {
final int BUFFER = 2048;
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);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
}
/*
* gets the last path component
*
* Example: getLastPathComponent("downloads/example/fileToZip");
* Result: "fileToZip"
*/
public String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
if (segments.length == 0)
return "";
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}
this is how I do it:
private static void zipFolder(String inputFolderPath, String outZipPath) {
try {
FileOutputStream fos = new FileOutputStream(outZipPath);
ZipOutputStream zos = new ZipOutputStream(fos);
File srcFile = new File(inputFolderPath);
File[] files = srcFile.listFiles();
Log.d("", "Zip directory: " + srcFile.getName());
for (int i = 0; i < files.length; i++) {
Log.d("", "Adding file: " + files[i].getName());
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(files[i]);
zos.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
}
zos.close();
} catch (IOException ioe) {
Log.e("", ioe.getMessage());
}
}
I have reworked the code from HailZeon to work properly under windows. Zip Entries must be closed before new ones are started and a starting "/" at entry names like "/file.txt" makes also problems
/**
* Zips a Folder to "[Folder].zip"
* #param toZipFolder Folder to be zipped
* #return the resulting ZipFile
*/
public static File zipFolder(File toZipFolder) {
File ZipFile = new File(toZipFolder.getParent(), format("%s.zip", toZipFolder.getName()));
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ZipFile));
zipSubFolder(out, toZipFolder, toZipFolder.getPath().length());
out.close();
return ZipFile;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* Main zip Function
* #param out Target ZipStream
* #param folder Folder to be zipped
* #param basePathLength Length of original Folder Path (for recursion)
*/
private static void zipSubFolder(ZipOutputStream out, File folder, int basePathLength) throws IOException {
final int BUFFER = 2048;
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 + 1);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
out.closeEntry();
}
}
}
Use the zip4j library from this location. Import the jar file to your "app/libs/" folder. And use the following code to zip your directories/files...
try {
File input = new File("path/to/your/input/fileOrFolder");
String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "zippedItem.zip";
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_STORE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
File output = new File(destinationPath);
ZipFile zipFile = new ZipFile(output);
// .addFolder or .addFile depending on your input
if (sourceFile.isDirectory())
zipFile.addFolder(input, parameters);
else
zipFile.addFile(input, parameters);
// Your input file/directory has been zipped at this point and you
// can access it as a normal file using the following line of code
File zippedFile = zipFile.getFile();
} catch (ZipException e) {
Log.e(TAG, Log.getStackTraceString(e));
}
If you use a java.util.zip object then you can write a script that does not modify the directory structure.
public static boolean zip(File sourceFile, File zipFile) {
List<File> fileList = getSubFiles(sourceFile, true);
ZipOutputStream zipOutputStream = null;
try {
zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFile));
int bufferSize = 1024;
byte[] buf = new byte[bufferSize];
ZipEntry zipEntry;
for(int i = 0; i < fileList.size(); i++) {
File file = fileList.get(i);
zipEntry = new ZipEntry(sourceFile.toURI().relativize(file.toURI()).getPath());
zipOutputStream.putNextEntry(zipEntry);
if (!file.isDirectory()) {
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
int readLength;
while ((readLength = inputStream.read(buf, 0, bufferSize)) != -1) {
zipOutputStream.write(buf, 0, readLength);
}
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
IoUtils.closeOS(zipOutputStream);
}
return true;
}
public static List<File> getSubFiles(File baseDir, boolean isContainFolder) {
List<File> fileList = new ArrayList<>();
File[] tmpList = baseDir.listFiles();
for (File file : tmpList) {
if (file.isFile()) {
fileList.add(file);
}
if (file.isDirectory()) {
if (isContainFolder) {
fileList.add(file); //key code
}
fileList.addAll(getSubFiles(file));
}
}
return fileList;
}
Just converting #HailZeon's answer to Kotlin:
import java.io.BufferedInputStream
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.ZipOutputStream
import java.util.zip.ZipException
private const val BUFFER = 2048
/**
* Compresses a file into a zip file
* #author Arnau Mora
* #since 20210318
* #param file The source file
* #param target The target file
*
* #throws NullPointerException If the entry name is null
* #throws IllegalArgumentException If the entry name is longer than 0xFFFF byte
* #throws SecurityException If a security manager exists and its SecurityManager.checkRead(String)
* method denies read access to the file
* #throws ZipException If a ZIP format error has occurred
* #throws IOException If an I/O error has occurre
*/
#Throws(
NullPointerException::class,
IllegalArgumentException::class,
SecurityException::class,
ZipException::class,
IOException::class
)
fun zipFile(file: File, target: File) {
val origin: BufferedInputStream
val dest: FileOutputStream
var zipOutput: ZipOutputStream? = null
try {
dest = target.outputStream()
zipOutput = ZipOutputStream(dest.buffered(BUFFER))
if (file.isDirectory)
zipSubFolder(zipOutput, file, file.parent!!.length)
else {
val data = ByteArray(BUFFER)
val fi = file.inputStream()
origin = fi.buffered(BUFFER)
val entry = ZipEntry(getLastPathComponent(file.path))
entry.time = file.lastModified()
zipOutput.putNextEntry(entry)
var count = origin.read(data, 0, BUFFER)
while (count != -1) {
zipOutput.write(data, 0, count)
count = origin.read(data, 0, BUFFER)
}
}
} finally {
zipOutput?.close()
}
}
private fun zipSubFolder(zipOutput: ZipOutputStream, folder: File, basePathLength: Int) {
val files = folder.listFiles() ?: return
var origin: BufferedInputStream? = null
try {
for (file in files) {
if (file.isDirectory)
zipSubFolder(zipOutput, folder, basePathLength)
else {
val data = ByteArray(BUFFER)
val unmodifiedFilePath = file.path
val relativePath = unmodifiedFilePath.substring(basePathLength)
val fi = FileInputStream(unmodifiedFilePath)
origin = fi.buffered(BUFFER)
val entry = ZipEntry(relativePath)
entry.time = file.lastModified()
zipOutput.putNextEntry(entry)
var count = origin.read(data, 0, BUFFER)
while (count != -1) {
zipOutput.write(data, 0, count)
count = origin.read(data, 0, BUFFER)
}
}
}
} finally {
origin?.close()
}
}
/*
* gets the last path component
*
* Example: getLastPathComponent("downloads/example/fileToZip");
* Result: "fileToZip"
*/
private fun getLastPathComponent(filePath: String): String {
val segments = filePath.split("/").toTypedArray()
return if (segments.isEmpty()) "" else segments[segments.size - 1]
}
If someone comes here trying to find a java8 cleaner refactored version of the #HailZeon code. Here it is:
private static final int BUFFER_SIZE = 2048;
public File zip(File source, String zipFileName) throws IOException {
File zipFile = null;
if(source != null) {
File zipFileDestination = new File(getCacheDir(), zipFileName);
if (zipFileDestination.exists()) {
zipFileDestination.delete();
}
zipFile = zip(source, zipFileDestination);
}
return zipFile;
}
public File zip(File source, File zipFile) throws IOException {
int relativeStartingPathIndex = zipFile.getAbsolutePath().lastIndexOf("/") + 1;
if (source != null && zipFile != null) {
try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(zipFile)))) {
if (source.isDirectory()) {
zipSubDir(out, source, relativeStartingPathIndex);
} else {
try (BufferedInputStream origin = new BufferedInputStream(new FileInputStream(source))) {
zipEntryFile(origin, out, source, relativeStartingPathIndex);
}
}
}
}
return zipFile;
}
private void zipSubDir(ZipOutputStream out, File dir, int relativeStartingPathIndex) throws IOException {
File[] files = dir.listFiles();
if (files != null) {
for(File file : files) {
if(file.isDirectory()) {
zipSubDir(out, file, relativeStartingPathIndex);
} else {
try (BufferedInputStream origin = new BufferedInputStream(new FileInputStream(file))) {
zipEntryFile(origin, out, file, relativeStartingPathIndex);
}
}
}
}
}
private void zipEntryFile(BufferedInputStream origin, ZipOutputStream out, File file, int relativeStartingPathIndex) throws IOException {
String relativePath = file.getAbsolutePath().substring(relativeStartingPathIndex);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
byte[] data = new byte[BUFFER_SIZE];
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
}