Creating a ZIP file with Android - android

How can I create a ZIP file from an XML file?
I want to take a backup of all my inbox messages in XML, and compress the XML file and store it on an SD card.

The following code solved my problem.
public class makeZip {
static final int BUFFER = 2048;
ZipOutputStream out;
byte data[];
public makeZip(String name) {
FileOutputStream dest=null;
try {
dest = new FileOutputStream(name);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out = new ZipOutputStream(new BufferedOutputStream(dest));
data = new byte[BUFFER];
}
public void addZipFile (String name) {
Log.v("addFile", "Adding: ");
FileInputStream fi=null;
try {
fi = new FileInputStream(name);
Log.v("addFile", "Adding: ");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("atch", "Adding: ");
}
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(name);
try {
out.putNextEntry(entry);
Log.v("put", "Adding: ");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int count;
try {
while((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
//Log.v("Write", "Adding: "+origin.read(data, 0, BUFFER));
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("catch", "Adding: ");
}
try {
origin.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeZip () {
try {
out.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

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" />

You may take a look at this two links:
ZipOutputStream http://developer.android.com/reference/java/util/zip/ZipOutputStream.html
Zipping files http://www.jondev.net/articles/Zipping_Files_with_Android_%28Programmatically%29
Hope this helps

The Android SDK has the gZip API, by which you can read/write conpressed data. See public class GZIPOutputStream.

Use the following code, but if you want to save to the SD card, do a fileoutputstream rather than bytearrayoutputstream.
private String compressData(String uncompressedData) {
String compressedData = null;
try {
if (uncompressedData.length() > 200) {
// Perform Compression.
byte[] originalBytes = uncompressedData.getBytes();
Deflater deflater = new Deflater();
deflater.setInput(originalBytes);
deflater.finish();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
while (!deflater.finished()) {
int byteCount = deflater.deflate(buf);
baos.write(buf, 0, byteCount);
}
deflater.end();
byte[] compressedBytes = baos.toByteArray();
compressedData = new String(compressedBytes, 0, compressedBytes.length);
}
}
catch (Exception e) {
compressedData = null;
}
return compressedData;
}

Related

Android Create zip file

I am using this piece of code to create a zip file:
String filename = Helper.Timestamp() + ".zip";
ZipOutputStream out = Helper.CreateZipOutputStream(filename);
Helper.AddZipFolder(out, Helper.ImageFolder);
Helper.AddZipFile(out, new File(Settings.FILENAME));
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Helper functions:
public static String Timestamp() { return new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); }
public static ZipOutputStream CreateZipOutputStream(String filename){
FileOutputStream dest = null;
try {
dest = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new ZipOutputStream(new BufferedOutputStream(dest));
}
public static void AddZipFolder(ZipOutputStream out, File folder){
for (File file: folder.listFiles()){
Helper.AddZipFile(out, file, folder.getName() + File.separator + file.getName());
}
}
public static void AddZipFile(ZipOutputStream out, File file){
AddZipFile(out, file, file.getName());
}
public static void AddZipFile(ZipOutputStream out, File file, String path){
byte[] data = new byte[1024];
FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
return;
}
try {
out.putNextEntry(new ZipEntry(path));
int len;
while ((len = in.read(data)) > 0)
out.write(data, 0, len);
out.closeEntry();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
However there seems to be something wrong with the out.write(data, 0, len); because there is a NullPointerException inside this function call. I believe this is due to the fact that my CreateZipOutputStream throws a FileNotFoundException.
So how should I properly create a zip file?
Because you forget to append base path on your filename. your filename must be like:
String filename = Environment.getExternalStorageDirectory().getPath() + "/" + Helper.Timestamp() + ".zip";

Save multiple images to sd card

My project has 30 images in drawable & I would like to save/copy all these images to sd card on a button click. I'm using below code to save image to sd card but I don't want to copy paste this code 30 times to save all the images. So is there any better solution for this problem. Thanks
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.aurora);
String fileName = "aurora.png";
File sd = Environment.getExternalStorageDirectory();
File folder = new File(sd + "/Wallpaper Pack");
folder.mkdir();
File dest = new File(folder, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Its very simple, create a array and loop it.
int[] drawablesArr = {R.id.name1, R.id.name2, ....}
for(int i=0l i<=drawablesArr.length; i++){
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), drawablesArr[i]);
String fileName = "image_"+ String.valueOf(i)+".png" ;
File sd = Environment.getExternalStorageDirectory();
File folder = new File(sd + "/Wallpaper Pack");
folder.mkdir();
File dest = new File(folder, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Murtaza Hussain's answer is right but it is better to run such operations out of UI (main) Thread. So, you can use ThreadPoolExecutor:
// SaveThread.java
public class SaveThread implements Runnable {
private int drawable;
private String fileName;
private Context context;
public SaveThread(Context context, int drawable, String fileName) {
this.drawable = drawable;
this.fileName = fileName;
this.context = context;
}
#override
public void run() {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawable);
File dest = new File(Environment.getExternalStorageDirectory(), "WallpaperPack/" + fileName);
dest.getParentFile().mkdirs();
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
then inside your activity or in other components:
int core = Runtime.getRuntime().availableProcessors();
ExecutorService executor =
new ThreadPoolExecutor(
core + 1,
core * 2 + 1,
60l,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
int[] drawables = {R.id.name1, R.id.name2, ....}
for(int drawable : drawables) {
executor.execute(new SaveThread(getApplicationContext(), drawable, "image_"+ drawable +".png"));
}
executor.shutdown();

how to copy a file with button

i know how to copy paste afile but with one button that make acopy and paste .
static void copyFile(String readFile,String writeFile ){
try {
FileInputStream fi = null;
FileOutputStream fo = null;
try {
fi = new FileInputStream(readFile);
fo = new FileOutputStream(writeFile);
//Read File
byte[] byt = new byte[fi.available()];
int r =0;
while((r=fi.read(byt))!=-1){
//fo.write(byt);
fo.write(byt, 0, r);
}
fi.close();
fo.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
finally{
}
but how to copy by one button and paste with another?
You can call method which copy file from source to path within your onClickEvent of your Button.
onClickEvent Handler snippet :
Button button1 = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
copy(filesrcpath, filedestpath); // Pass Filesrc and FilePath
}
});
Copy() snippet which takes two parameter one source and another destination path.
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();
}

Unable to export sqlite DB to sdcard

I have been trying to export my database file into the external memory of my android phone by using
private final String DB_NAME = "MemberData";
private final String TABLE_NAME = "MemberDB";
//Get a reference to the database
File dbFile = this.getDatabasePath(DB_NAME);
//Get a reference to the directory location for the backup
File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File backup = new File(exportDir, dbFile.getName());
//Check the required operation String command = params[0];
//Attempt file copy
try {
backup.createNewFile();
fileCopy(dbFile, backup);
} catch (IOException e) {
/*Handle File Error*/
}
private void fileCopy(File source, File dest) throws IOException {
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(dest).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null) inChannel.close();
if (outChannel != null) outChannel.close();
}
}
It managed to create a directory name "myappsbackup" but my database couldnt be copied over. it is always size 0 and my tables are missing. Is there something wrong with my method of copying?
Here is the code I use to write or backup my SQLite db to the sdcard.
try {
db.open();
File newFile = new File("/sdcard/Your File Name Here");
InputStream input = new FileInputStream(
"/data/data/com.packageNameHere/databases/DB Name Here");
OutputStream output = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
db.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Download zip file and save it in sdcard

I have an application to download zip file and save to sdcard. But I get zipentry=null while reading inputstream, it doesn't enter the while block. Could anyone help me in solving this problem, please?
try {
// fileInputStream = new InputStream(input);
ZipInputStream zipInputStream
= new ZipInputStream(new BufferedInputStream(input));
ZipEntry zipEntry=zipInputStream.getNextEntry();
Toast.makeText(getApplicationContext(), "I have entered try block zipentry"+zipEntry,Toast.LENGTH_LONG).show();
System.out.println("Zipentry is"+zipEntry);
while ((zipEntry = zipInputStream.getNextEntry()) != null){
Toast.makeText(getApplicationContext(), "Entered into while block",Toast.LENGTH_LONG).show();
String zipEntryName = zipEntry.getName();
File file = new File(to + 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
Toast.makeText(getApplicationContext(), "File not found",Toast.LENGTH_LONG).show();
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Input outout error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
You already have one ZipEntry zipEntry=zipInputStream.getNextEntry(); before condition in the while loop. Leave it out and initialize it only in the while loop. Something like:
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null){
//
}

Categories

Resources