How to zip the files in android - android

I have a requirement to zip the text files programatically.
I have created text files at files directory(context.getFilesDirectory()),
I want zip the text files and add the zipped file to the Intent object.
Please provide me a piece of code to how to zip the files in android.

If you have a FOLDER in SDCard and you want to create a zip of it, then simply copy and paste this code in your project and it will give you a zip Folder. This code will create a zip of the folder which only contains files no nested folder should be inside. You can further modify for your self.
String []s=new String[2]; //declare an array for storing the files i.e the path of your source files
s[0]="/mnt/sdcard/Wallpaper/pic.jpg"; //Type the path of the files in here
s[1]="/mnt/sdcard/Wallpaper/Final.pdf"; // path of the second file
zip((s,"/mnt/sdcard/MyZipFolder.zip"); //call the zip function
public void zip(String[] files, String zipFile)
{
private String[] _files= files;
private String _zipFile= zipFile;
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.d("add:",_files[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();
}
}
Also add permissions in android-manifest.xml using this code
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />

If you want to compress files with password you can take a look at this library you need to add this lines to your build.gradle:
dependencies {
compile 'com.github.ghost1372:Mzip-Android:0.4.0'
}
here is the code to zip files:
Zip:
ZipArchive zipArchive = new ZipArchive();
zipArchive.zip(targetPath,destinationPath,password);
//This Library is dead as it is not avaialable on github anymore

This is working code for zipping the files. You have to add all the file paths which you want to zip into the arrayList and send it as parameter to below function along with string name for zipfile you want.
public String zipper(ArrayList<String> allFiles, String zipFileName) throws IOException
{
timeStampOfZipFile =new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
App.mediaStorageDir.mkdirs();
zippath = App.mediaStorageDir.getAbsolutePath() + "/" + zipFileName+ timeStampOfZipFile + ".zip";
try
{
if (new File(zippath).exists())
{
new File(zippath).delete();
}
//new File(zipFileName).delete(); // Delete if exists
ZipFile zipFile = new ZipFile(zippath);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParameters.setPassword("Reset");
if (allFiles.size() > 0)
{
for (String fileName : allFiles)
{
File file = new File(fileName);
zipFile.addFile(file, zipParameters);
}
}
}
catch (ZipException e)
{
e.printStackTrace();
}
return zippath;
}
Here App.mediaStorageDir.mkdirs();
where mediaStorage is static final string in my App.class
public static final File mediaStorageDir = new File(Environment.getExternalStorageDirectory(),
"yourAppFoler");
creates directory where the zip file will be saved. Result of function returns zip file path which can be used to attach to multipart entity for sending it to server(if you wish).
Requires run time permission for API>=marshmellow
<!-- == External Storage == -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Related

Empty Folders are not adding to zip file android

I am doing an Android project. I need to zip a complete folder structure of SD card.
code is able to zip the folder if any files exists inside the folder, else skips that folder.
My Folder structure is like: mnt/sdcard/Movies/Telugu/Files.
mnt/sdcard/Movies/English --> English is empty folder
I did not see English folder in output zip file.
My code:
public void zip() {
try {
// create a ZipOutputStream to zip the data to
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
_zipFile));
zipDir(folderPath, zos);
// close the stream
zos.close();
} catch (Exception e) {
// handle exception
}
}
public void zipDir(String dir2zip, ZipOutputStream zos) {
try {
File zipDir = new File(dir2zip);
// get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// loop through dirList, and zip the files
for (int i = 0; i < dirList.length; i++) {
File f = new File(zipDir, dirList[i]);
if (f.isDirectory()) {
// if the File object is a directory, call this
// function again to add its content recursively
String filePath = f.getPath();
zipDir(filePath, zos);
// loop again
continue;
}
// if we reached here, the File object f was not a directory
// create a FileInputStream on top of f
FileInputStream fis = new FileInputStream(f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath());
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
// now write the content of the file to the ZipOutputStream
while ((bytesIn = fis.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesIn);
}
// close the Stream
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
// handle exception
}
}
Please help..
You basically never create a zipentry for your directories.
In the if (f.isDirectory()) {} section, add this:
zos.putNextEntry(new ZipEntry(filePath));
You can also put it at the beginning of the method instead, to include the root dir as well.
It's old post but it will be good for who searching to solve problem.
You have just add dirName+"/", Yes you need just one slash to end of folder name string.
if(dirList.length==0){
String path=zipDir.getPath().replace(rootDir,"");
ZipEntry anEntry = new ZipEntry(path+"/");
zos.putNextEntry(anEntry);
}

File copying: what am I doing wrong?

Sorry,
I have no experience with the Android file system, I am struggling to understand it via the documentation and the tutorials.
I am trying to copy a file from a location to the external storage of my app.
final File filetobecopied =item.getFile();
File path=getPrivateExternalStorageDir(mContext);
final File destination = new File(path,item.getName());
try
{copy(filetobecopied,destination);
}
catch (IOException e) {Log.e("",e.toString());}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Toast.makeText(mContext,"COPIED",Toast.LENGTH_SHORT).show();
}
public File getPrivateExternalStorageDir(Context context) {
File file = context.getExternalFilesDir(null);
if (!file.mkdirs()) {
Log.e("", "Directory not created");
}
return file;
}
I get the following error:
09-18 10:14:04.260: E/(7089): java.io.FileNotFoundException: /storage/emulated/0/Android/data/org.openintents.filemanager/files/2013-08-24 13.18.14.jpg: open failed: EISDIR (Is a directory)
http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String) use this example of code and use standart examples of google)
Try
final File destination = new File(path + "/" + item.getName());
instead.
I assume, folder directory is not created or your external storage state is not mounted.
Before you perform file operations, you should sanitize your path. Following code is a sample code that I often use.
public File sanitizePath(Context context) {
String state = android.os.Environment.getExternalStorageState();
File folder = null;
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
folder = new File(context.getFilesDir() + path);
// path is the desired location that must be specified in your code.
}else{
folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + path);
}
if (!folder.exists()){
folder.mkdirs();
}
return folder;
}
And be sure about that, when your directory has to be created before you perform file operations.
Hope this will help.
EDIT: By the way, you have to add following permission to your manifest.xml file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

How to compress a folder to make docx file in android?

I'm trying to make an Android application that can open a docx file to read, edit and save it.
My idea is to extract all the xml file within the archive to a temp folder. In this folder we can edit the content of the docx in /word/document.xml. The problem is when I compress this temp folder to make a new docx file and replace the old file, inside the new docx archive the path is like /mnt/sdcard/temp/"all files xml go here" while the xml files should be in the first level.
Can anybody help me to go through this? here is the method to compress the temp directory
Note: dir2zip argument's value I use is /mnt/sdcard/temp/***.docx
public void zipDir(String dir2zip, ZipOutputStream zos)
{
try
{
//create a new File object based on the directory we
//have to zip File
File zipDir = new File(dir2zip);
//get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
//loop through dirList, and zip the files
for(int i=0; i<dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if(f.isDirectory())
{
//if the File object is a directory, call this
//function again to add its content recursively
String filePath = f.getPath();
zipDir(filePath, zos);
//loop again
continue;
}
//if we reached here, the File object f was not a directory
//create a FileInputStream on top of f
FileInputStream fis = new FileInputStream(f);
//create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath());
//place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
//now write the content of the file to the ZipOutputStream
while((bytesIn = fis.read(readBuffer)) != -1)
{
zos.write(readBuffer, 0, bytesIn);
}
//close the Stream
fis.close();
}
}
catch(Exception e)
{
//handle exception
}
}
I have managed to fix it by myself. The problem is in this line:
File f = new File(zipDir, dirList[i]);
It should be
File f = new File(dirList[i]);
If the argument zipDir is included, the absolute path to the directory will be used in the archive!
I have now managed to get the original poster's code working on Mac and Windows by making the following two modifications:
1: add a ZipEntry for each directory: do not simply ignore it
2: remove the directory name from the ZipEntry name
Note: zipinfo is useful
This is a program that works for me:
import java.io.*;
import java.util.zip.*;
public class zipdoc
{
String savedDir = null;
public void zipDir(String dir2zip, ZipOutputStream zos)
{
try
{
if (savedDir == null)
savedDir = dir2zip;
// create a new File object based on the directory we
// have to zip File
File zipDir = new File(dir2zip);
//get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// loop through dirList, and zip the files
for (int i=0; i<dirList.length; i++)
{
File f = new File(zipDir, dirList[i]);
if (f.isDirectory())
{
// if the File object is a directory, call this
// function again to add its content recursively
System.out.println("Adding dir: " + f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath().substring(savedDir.length()+1) + "/");
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
String filePath = f.getPath();
zipDir(filePath, zos);
// loop again
continue;
}
else if (!f.getName().equals(".DS_Store"))
{
// if we reached here, the File object f was not a directory
// and it's not the MacOSX special .DS_Store
// create a FileInputStream on top of f
System.out.println("Adding file: " + f);
FileInputStream fis = new FileInputStream(f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath().substring(savedDir.length()+1));
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
// now write the content of the file to the ZipOutputStream
while((bytesIn = fis.read(readBuffer)) != -1)
{
zos.write(readBuffer, 0, bytesIn);
}
// close the Stream
fis.close();
}
}
}
catch(Exception e)
{
// handle exception
System.out.println(e);
}
}
public void zipit(String inDir, String outFile)
{
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(outFile)));
zos.setMethod(0);
zos.setMethod(ZipOutputStream.DEFLATED);
zos.setLevel(0);
zipDir(inDir, zos);
zos.finish();
zos.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
public static void main (String args[]) {
zipdoc z1 = new zipdoc();
// Check there are sufficient params if desired
// first param is directory to be 'zipped', second is resulting
// filename (??.docx)
// eg java zipdoc dir1 newDoc.docx
z1.zipit(args[0], args[1]);
System.out.println("Finished creating " + args[1]);
}
}

Replace a character in a file and copy the contents to a temp file and rename the temp file to original file

I want to replace a character in a file and copy the contents to a temp file and rename the temp file to original file.
path = "/mnt/sdcard/TESTfile/"
File _f = new File(path);
File[] _f1 = _f.listFiles();
String[] s1 = { "t1.txt", "t2.txt", "t3.txt" };
_fOut = new FileOutputStream(path + File.separator + s1[i]);
// Copy the bits from input stream to output stream
StringBuffer sb = null;
BufferedWriter out = null;
while ((line = reader.readLine()) != null) {
line = line.replaceAll("a"," ").replaceAll("g"," ");
sb = new StringBuffer();
Log.i("Line>>>" + line, "<<<<<");
sb.append(line);
s = sb.toString();
byte[] temp = s.getBytes();
_fOut.write(temp);
}
fis.close();
_fOut.close();
//old file name with path
String path1 = path + File.separator + s1[i];
//new file name with path
String rename1 = path + File.separator + _f1[i].getName();
File oldFile = new File(path1);
File renameFile = new File(rename1);
for(int j = 0; j < _f1.length;j++)
{
oldFile.renameTo(renameFile);
}
This is how i tried to do it. I am not sure how to rename the file and delete the original file. Please help
To rename a file, you need 2 File objects. Create one using the original path and the second using the new name. Then call original.renameTo(newFile).
Deleting a file is even easier. Android contexts have a method called deleteFile(name). Call it to delete a file. Keep in mind that that method deletes a file from the local storage folders only and doesn't accept path separators. If you want to delete a file from a different location, there is a file.delete() method you could use too.

How to load the local html page using intent in Android?

I have a html file in my asset directory and i have to load it as browser application using Intent.
Here is my code, but its not working:
startActivity (new Intent(Intent.ACTION_VIEW,
Uri.parse("file:///android_asset/Sample.htm")));
Could anyone help me?
Use loadUrl() method of WebView to load an html page
Sample Example
if faq.html is the html file present in assets folder then you can use
WebView html = (WebView) findViewById(R.id.webEulaView);
html.loadUrl("file:///android_asset/faq.html");
i had the same problem what i did was
copied the content of the assets to a database and then pulled it from the sdcard
here is the code to copy your assets to sdcard
the logic used is as follows the html pages are put in the zip file in assets folder
content is the name of the zip in assets folder
boolean succussFlag = false;
destination="";
destination=Environment.getExternalStorageDirectory()+"/";
File file = new File(destination);
if (!file.exists()){
file.mkdirs();
}
else
{
//file.delete();
//file.mkdir();
}
try
{
InputStream fileInput = context.getAssets().open("content.zip");
ZipInputStream inputStream = new ZipInputStream(fileInput);
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream.getNextEntry())
{
String innerFileName = destination + entry.getName();
System.out.println("destination::::"+innerFileName);
// Log.v("inner file name 0",""+innerFileName);
File innerFile = new File(innerFileName);
if (innerFile.exists())
{
innerFile.delete();
}
// Check if it is a folder
if (entry.isDirectory())
{
// Its a folder, create that folder
innerFile.mkdirs();
}
else
{
// System.out.println(" ::::::::::::::INNER FILE COPYING :::: " + innerFile.toString());
FileOutputStream outputStream = new FileOutputStream(innerFileName);
final int BUFFER = 4096;
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream,
BUFFER);
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1)
{
bufferedOutputStream.write(data, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
inputStream.closeEntry();
}
inputStream.close();
// System.out.println(" ::::::::::COPIED TO PRIVATE FOLDER :::: " );
succussFlag=true;
}
catch (IOException e)
{
// System.out.println("** EXCEPTION OCCURED WHILE COPYING***");
e.printStackTrace();
succussFlag=false;
}
return succussFlag;
after this you give following command
startActivity (new Intent(Intent.ACTION_VIEW,"file://"+ Environment.getExternalStorageDirectory()+"/content"+name_Html ;
);

Categories

Resources