Android - Unzip a folder? - android

I have a zip folder on my SD card, how do i unzip the folder (within my application code) ?

I am using a modified version of Beginner's method that extends AsyncTask and can update Observers on the main thread. Byte by byte compression is extremely slow and should be avoided. Instead a more efficient approach is to copy large chunks of data to the output stream.
package com.blarg.webviewscroller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Observable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import android.os.AsyncTask;
import android.util.Log;
public class UnZipper extends Observable {
private static final String TAG = "UnZip";
private String mFileName, mFilePath, mDestinationPath;
public UnZipper (String fileName, String filePath, String destinationPath) {
mFileName = fileName;
mFilePath = filePath;
mDestinationPath = destinationPath;
}
public String getFileName () {
return mFileName;
}
public String getFilePath() {
return mFilePath;
}
public String getDestinationPath () {
return mDestinationPath;
}
public void unzip () {
String fullPath = mFilePath + "/" + mFileName + ".zip";
Log.d(TAG, "unzipping " + mFileName + " to " + mDestinationPath);
new UnZipTask().execute(fullPath, mDestinationPath);
}
private class UnZipTask extends AsyncTask<String, Void, Boolean> {
#SuppressWarnings("rawtypes")
#Override
protected Boolean doInBackground(String... params) {
String filePath = params[0];
String destinationPath = params[1];
File archive = new File(filePath);
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, destinationPath);
}
} catch (Exception e) {
Log.e(TAG, "Error while extracting file " + archive, e);
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
setChanged();
notifyObservers();
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry,
String outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()) {
createDir(outputFile.getParentFile());
}
Log.v(TAG, "Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
if (dir.exists()) {
return;
}
Log.v(TAG, "Creating dir " + dir.getName());
if (!dir.mkdirs()) {
throw new RuntimeException("Can not create dir " + dir);
}
}
}
}
It is used by a class that implements Observer, such as:
private void unzipWebFile(String filename) {
String unzipLocation = getExternalFilesDir(null) + "/unzipped";
String filePath = Environment.getExternalStorageDirectory().toString();
UnZipper unzipper = new UnZipper(filename, filePath, unzipLocation);
unzipper.addObserver(this);
unzipper.unzip();
}
Your observer will get an update(Observable observable, Object data) callback when the unzip finishes.

static Handler myHandler;
ProgressDialog myProgress;
public void unzipFile(File zipfile) {
myProgress = ProgressDialog.show(getContext(), "Extract Zip",
"Extracting Files...", true, false);
File zipFile = zipfile;
String directory = null;
directory = zipFile.getParent();
directory = directory + "/";
myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// process incoming messages here
switch (msg.what) {
case 0:
// update progress bar
myProgress.setMessage("" + (String) msg.obj);
break;
case 1:
myProgress.cancel();
Toast toast = Toast.makeText(getContext(),
"Zip extracted successfully",
Toast.LENGTH_SHORT);
toast.show();
provider.refresh();
break;
case 2:
myProgress.cancel();
break;
}
super.handleMessage(msg);
}
};
Thread workthread = new Thread(new UnZip(zipFile, directory));
workthread.start();
}
public class UnZip implements Runnable {
File archive;
String outputDir;
public UnZip(File ziparchive, String directory) {
archive = ziparchive;
outputDir = directory;
}
public void log(String log) {
Log.v("unzip", log);
}
#SuppressWarnings("unchecked")
public void run() {
Message msg;
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries();
e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
msg = new Message();
msg.what = 0;
msg.obj = "Extracting " + entry.getName();
myHandler.sendMessage(msg);
unzipEntry(zipfile, entry, outputDir);
}
} catch (Exception e) {
log("Error while extracting file " + archive);
}
msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
}
#SuppressWarnings("unchecked")
public void unzipArchive(File archive, String outputDir) {
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries();
e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, outputDir);
}
} catch (Exception e) {
log("Error while extracting file " + archive);
}
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry,
String outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()) {
createDir(outputFile.getParentFile());
}
log("Extracting: " + entry);
BufferedInputStream inputStream = new
BufferedInputStream(zipfile
.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
log("Creating dir " + dir.getName());
if (!dir.mkdirs())
throw new RuntimeException("Can not create dir " + dir);
}
}
This is what worked for me thanks people

just "addon" for #rich.e answer:
in doInBackground() after iterating through ZipEtries you should close the file, because sometimes you want do delete the file after unzipping it and it throws an exception if file was not closed:
try {
ZipFile zipfile = new ZipFile(archive);
int entries = zipfile.size();
int total = 0;
if(onZipListener != null)
onZipListener.onUncompressStart(archive);
for (Enumeration<?> e = zipfile.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(onZipListener != null)
onZipListener.onUncompressProgress(archive, (int) (total++ * 100 / entries));
unzipEntry(zipfile, entry, path);
}
zipfile.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

Android - Unable to unzip downloaded zip file - UTFDataFormatException

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();
}
}
}

How can I modify the code to upload multiple files using NanoHTTPD in Android?

I'm a beginner of NanoHTTPD, I learned the documents NanoHttpd save uploaded files and https://github.com/romsahel/simplewebserver
The following code can upload a single file to android mobile phone via WiFi.
Now I hope to upload multiple files to android mobile phone, how can I modify the following code to do that? Thanks!
package com.wade.webserver;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyServer extends NanoHTTPD {
private final static int PORT = 8189;
private String rootDir = null;
#SuppressWarnings("serial")
public static final List<String> INDEX_FILE_NAMES = new ArrayList<String>() {
{
add("index.html");
add("index.htm");
}
};
public MyServer() throws IOException {
super(PORT);
File f;
f = new File("/storage/sdcard0/www");
if (f.canWrite()) {
rootDir = "/storage/sdcard0/www";
System.out.println("rootDir = " + rootDir);
}
else {
f = new File("/storage/sdcard1/www");
if (f.canWrite()) {
rootDir = "/storage/sdcard1/www";
System.out.println("rootDir = " + rootDir);
}
else {
rootDir = "/storage/sdcard0";
System.out.println("set rootDir default " + rootDir);
}
}
start(NanoHTTPD.SOCKET_READ_TIMEOUT);
}
#Override
public Response serve(IHTTPSession session)
{
Map<String, String> header = session.getHeaders();
Map<String, String> parms = session.getParms();
Method method = session.getMethod();
String uri = session.getUri();
System.out.println(method + " '" + uri + "' ");
if (Method.POST.equals(method) || Method.PUT.equals(method))
handlePost(session, parms);
File file = new File(rootDir + uri);
if (!file.exists()) {
return getNotFoundResponse();
}
if (file.isDirectory())
return listDirectory(file, header, uri);
else
return downloadFile(file);
}
private Response handlePost(IHTTPSession session, Map<String, String> parms)
{
Map<String, String> files = new HashMap<>();
try
{
session.parseBody(files);
final File src = new File(files.get("filename"));
// final File dst = new File(rootDir, parms.get("filename"));
//final File mydst = new File(parms.get("filename"));
String myString=parms.get("filename");
String fileName = myString.substring(myString.lastIndexOf("\\")+1);
String s = "/storage/sdcard0/www/"+fileName;
final File dst = new File(s);
//Files.copy(src.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
try {
copy(src, dst);
}catch (Exception e){
Log.e("CW","Error");
e.printStackTrace();
}
System.out.println(src.getAbsolutePath() + ": uploaded to: " + dst.getAbsolutePath());
return newFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, "ok i am ");
} catch (IOException ex)
{
} catch (ResponseException ex)
{
}
return getNotFoundResponse();
}
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();
}
private Response downloadFile(File file)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(file);
} catch (FileNotFoundException ex)
{
// Logger.getLogger(MyWebServer.class.getName()).log(Level.SEVERE, null, ex);
}
return newFixedLengthResponse(Response.Status.OK, "application/octet-stream", fis, file.getTotalSpace());
}
private Response listDirectory(File file, Map<String, String> header, String uri)
{
String htmlCode = "<li>%s</li>";
StringBuilder message = new StringBuilder("<ul>");
for (File f : file.listFiles())
message.append(String.format(htmlCode, header.get("host") + uri + f.getName(), f.getName()));
message.append("</ul>");
message.append("<form method=\"post\" enctype=\"multipart/form-data\">\n"
+ " <input type=\"file\" name=\"filename\" />\n"
+ " <input type=\"submit\" value=\"Send\" />\n"
+ "</form>");
return mynewFixedLengthResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, message.toString());
}
//#Override
private Response mynewFixedLengthResponse(Response.IStatus status, String mimeType, String message)
{
Response response = super.newFixedLengthResponse(status, mimeType, message);
response.addHeader("Accept-Ranges", "bytes");
return response;
}
protected Response getNotFoundResponse()
{
return newFixedLengthResponse(Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found.");
}
}
I did it like this:
public Response serve(IHTTPSession session) {
if (uri.toLowerCase().contains("add_file".toLowerCase())) {
Method method = session.getMethod();
if (Method.PUT.equals(method) || Method.POST.equals(method)) {
try {
Map<String, String> files = new HashMap<>();
session.parseBody(files);
} catch (IOException ioe) {
return newFixedLengthResponse(Response.Status.INTERNAL_ERROR, NanoHTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage());
} catch (ResponseException re) {
return newFixedLengthResponse(re.getStatus(), NanoHTTPD.MIME_PLAINTEXT, re.getMessage());
}
}
HelloServer.LOGCONSOLE.info(method + " '" + uri + "' ");
String msg = upload(session);
return newFixedLengthResponse(msg);
}
public upload(IHTTPSession session){
Map<String, String> parms = session.getParms();
// recuperate file names
String file1 = parms.get("input_file");
String file2 = parms.get("filename1");
String file3 = parms.get("myFile2");
// you must put numbers if file number more than 1
// source file is located in the temporary directory
// you can modify your temp direcory by eiditing NanoHTTPD.saveTmpFile
...
return String ... ;

Unzip File in Android Assets

I put a zip file in the android assets. How do i extract the file in the android internal storage? I know how to get the file, but i don't know how to extract it. This is my code..
Util zip ;
zip = new Util();
zip.copyFileFromAsset(this, "myfile.zip", getExternalStorage()+
"/android/data/edu.binus.profile/");
Thanks for helping :D
This piece of code will help you....Just pass the zipfile location and the location where you want the extracted files to be saved to this class while making an object...and call unzip method...
public class Decompress {
private String zip;
private String loc;
public Decompress(String zipFile, String location) {
zip = zipFile;
loc = location;
dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(zip);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(loc + ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
Based on Sreedev R solution,
I added the option to read the file from assets and use buffer:
package com.pixoneye.api.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.content.Context;
import android.util.Log;
public class Decompress {
private static final int BUFFER_SIZE = 1024 * 10;
private static final String TAG = "Decompress";
public static void unzipFromAssets(Context context, String zipFile, String destination) {
try {
if (destination == null || destination.length() == 0)
destination = context.getFilesDir().getAbsolutePath();
InputStream stream = context.getAssets().open(zipFile);
unzip(stream, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void unzip(String zipFile, String location) {
try {
FileInputStream fin = new FileInputStream(zipFile);
unzip(fin, location);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void unzip(InputStream stream, String destination) {
dirChecker(destination, "");
byte[] buffer = new byte[BUFFER_SIZE];
try {
ZipInputStream zin = new ZipInputStream(stream);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v(TAG, "Unzipping " + ze.getName());
if (ze.isDirectory()) {
dirChecker(destination, ze.getName());
} else {
File f = new File(destination, ze.getName());
if (!f.exists()) {
boolean success = f.createNewFile();
if (!success) {
Log.w(TAG, "Failed to create file " + f.getName());
continue;
}
FileOutputStream fout = new FileOutputStream(f);
int count;
while ((count = zin.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
zin.closeEntry();
fout.close();
}
}
}
zin.close();
} catch (Exception e) {
Log.e(TAG, "unzip", e);
}
}
private static void dirChecker(String destination, String dir) {
File f = new File(destination, dir);
if (!f.isDirectory()) {
boolean success = f.mkdirs();
if (!success) {
Log.w(TAG, "Failed to create folder " + f.getName());
}
}
}
}
Maybe you should try using a FileOutputStream in combination with an inputstream from the zip file. With a package file, this should work.
To quote #wordy from this question:
PackageManager pm = context.getPackageManager();
String apkFile = pm.getApplicationInfo(context.getPackageName(), 0).sourceDir;
ZipFile zipFile = new ZipFile(apkFile);
ZipEntry entry = zipFile.getEntry("assets/FILENAME");
myInput = zipFile.getInputStream(entry);
myOutput = new FileOutputStream(file);
byte[] buffer = new byte[1024*4];
int length;
int total = 0;
int counter = 1;
while ((length = myInput.read(buffer)) > 0) {
total += length;
counter++;
if (counter % 32 == 0) {
publishProgress(total);
}
myOutput.write(buffer, 0, length);
}
Looks like there may be problems with ProGuard but hopefully the code sample works for you.
I haven't tested yet,but while doing a project on OCR I came across this library,where there is method of unzipping a downloaded file from the net. The exact method for unzipping file is installZipFromAssets(String sourceFilename,File destinationDir,File destinationFile) found under this class.Hope this is what you are looking for
You can also make use of the zip4j external library that provides additional features like encryption. Also, it has functions to extract files to a particular location provided the path.

unzippping of zipped files fails for android using code which are zipped from Mac system

In my application i am downloading zipped from a server and extracting the files through code here but the zip files contains .DS_store file and so my unzipping fails . Is there a way to avoid it.
/*/////
public class Decompress {
private String _zipFile;
private String _location;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public boolean unZip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
byte[] buffer = new byte[1024];
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
// for (int c = zin.read(); c != -1; c = zin.read(buffer,0,1024)) {
// fout.write(buffer,0,c);
// }
int c;
while (( c = zin.read(buffer,0,1024)) >= 0) {
fout.write(buffer,0,c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
return false;
}
return true;
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
////
*/
use this code
public class ZipHelper
{
boolean zipError=false;
public boolean isZipError() {
return zipError;
}
public void setZipError(boolean zipError) {
this.zipError = zipError;
}
public boolean unzip(String archive, File outputDir)
{
try {
Log.d("control","ZipHelper.unzip() - File: " + archive);
ZipFile zipfile = new ZipFile(archive);
for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, outputDir);
}
return true;
}
catch (Exception e) {
Log.d("control","ZipHelper.unzip() - Error extracting file " + archive+": "+ e);
setZipError(true);
return false;
}
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException
{
if (entry.isDirectory()) {
createDirectory(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()){
createDirectory(outputFile.getParentFile());
}
Log.d("control","ZipHelper.unzipEntry() - Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
}
catch (Exception e) {
Log.d("control","ZipHelper.unzipEntry() - Error: " + e);
setZipError(true);
}
finally {
outputStream.close();
inputStream.close();
}
}
private void createDirectory(File dir)
{
Log.d("control","ZipHelper.createDir() - Creating directory: "+dir.getName());
if (!dir.exists()){
if(!dir.mkdirs()) throw new RuntimeException("Can't create directory "+dir);
}
else Log.d("control","ZipHelper.createDir() - Exists directory: "+dir.getName());
}
}
call this class like this
final String exportDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
+"/destination file/name/";
final String exportDirectoryArchivefile = Environment.getExternalStorageDirectory().getAbsolutePath()
+"/original/file name/"+name;
final File exportDirectoryFilepath = new File(exportDirectory);
exportDirectoryFilepath.mkdirs();
final File exportDirectoryFilepathArchive = new File(exportDirectoryArchivefile);
boolean flag_unzip =zh.unzip(exportDirectoryArchivefile, exportDirectoryFilepath);

File operation in android

I am new to android platform. I need to create a text file in android. Please let me know how to perform this task in android. I have written a code that is working fine in java but not in android. Please help me on this....the sample code that ihave written is :-
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.txt", true));
dos.writeBytes(dataLine);
dos.close();
}
catch (FileNotFoundException ex) {}
the above code snippet is working fine in java but not in android :(
Thanks,
Ashish
The Android Dev Guide explains it nicely:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
If you want the files you create to be visible to the outside world, use external storage. But as I said in the comment, make sure you're "being a good citizen". These files stick around even after the user uninstalls your app.
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
/**
* Static methods used for common file operations.
*
* #author Carl Hartung (carlhartung#gmail.com)
*/
public class FileUtils {
private final static String t = "FileUtils";
// Used to validate and display valid form names.
public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";
// Storage paths
public static final String FORMS_PATH = Environment.getExternalStorageDirectory() + "/odk/forms/";
public static final String INSTANCES_PATH = Environment.getExternalStorageDirectory() + "/odk/instances/";
public static final String CACHE_PATH = Environment.getExternalStorageDirectory() + "/odk/.cache/";
public static final String TMPFILE_PATH = CACHE_PATH + "tmp.jpg";
public static ArrayList<String> getValidFormsAsArrayList(String path) {
ArrayList<String> formPaths = new ArrayList<String>();
File dir = new File(path);
if (!storageReady()) {
return null;
}
if (!dir.exists()) {
if (!createFolder(path)) {
return null;
}
}
File[] dirs = dir.listFiles();
for (int i = 0; i < dirs.length; i++) {
// skip all the directories
if (dirs[i].isDirectory())
continue;
String formName = dirs[i].getName();
formPaths.add(dirs[i].getAbsolutePath());
}
return formPaths;
}
public static ArrayList<String> getFoldersAsArrayList(String path) {
ArrayList<String> mFolderList = new ArrayList<String>();
File root = new File(path);
if (!storageReady()) {
return null;
}
if (!root.exists()) {
if (!createFolder(path)) {
return null;
}
}
if (root.isDirectory()) {
File[] children = root.listFiles();
for (File child : children) {
boolean directory = child.isDirectory();
if (directory) {
mFolderList.add(child.getAbsolutePath());
}
}
}
return mFolderList;
}
public static boolean deleteFolder(String path) {
// not recursive
if (path != null && storageReady()) {
File dir = new File(path);
if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.delete()) {
Log.i(t, "Failed to delete " + file);
}
}
}
return dir.delete();
} else {
return false;
}
}
public static boolean createFolder(String path) {
if (storageReady()) {
boolean made = true;
File dir = new File(path);
if (!dir.exists()) {
made = dir.mkdirs();
}
return made;
} else {
return false;
}
}
public static boolean deleteFile(String path) {
if (storageReady()) {
File f = new File(path);
return f.delete();
} else {
return false;
}
}
public static byte[] getFileAsBytes(File file) {
byte[] bytes = null;
InputStream is = null;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
// Create the byte array to hold the data
bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int read = 0;
try {
while (offset < bytes.length && read >= 0) {
read = is.read(bytes, offset, bytes.length - offset);
offset += read;
}
} catch (IOException e) {
Log.e(t, "Cannot read " + file.getName());
e.printStackTrace();
return null;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
try {
throw new IOException("Could not completely read file " + file.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return bytes;
} catch (FileNotFoundException e) {
Log.e(t, "Cannot find " + file.getName());
e.printStackTrace();
return null;
} finally {
// Close the input stream
try {
is.close();
} catch (IOException e) {
Log.e(t, "Cannot close input stream for " + file.getName());
e.printStackTrace();
return null;
}
}
}
public static boolean storageReady() {
String cardstatus = Environment.getExternalStorageState();
if (cardstatus.equals(Environment.MEDIA_REMOVED)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTED)
|| cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
return false;
} else {
return true;
}
}
public static String getMd5Hash(File file) {
try {
// CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
MessageDigest md = MessageDigest.getInstance("MD5");
int chunkSize = 256;
byte[] chunk = new byte[chunkSize];
// Get the size of the file
long lLength = file.length();
if (lLength > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
int length = (int) lLength;
InputStream is = null;
is = new FileInputStream(file);
int l = 0;
for (l = 0; l + chunkSize < length; l += chunkSize) {
is.read(chunk, 0, chunkSize);
md.update(chunk, 0, chunkSize);
}
int remaining = length - l;
if (remaining > 0) {
is.read(chunk, 0, remaining);
md.update(chunk, 0, remaining);
}
byte[] messageDigest = md.digest();
BigInteger number = new BigInteger(1, messageDigest);
String md5 = number.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
is.close();
return md5;
} catch (NoSuchAlgorithmException e) {
Log.e("MD5", e.getMessage());
return null;
} catch (FileNotFoundException e) {
Log.e("No Cache File", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Problem reading from file", e.getMessage());
return null;
}
}
}
Try this
final File sdcard=Environment.getExternalStorageDirectory();
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
File path=new File(sdcard,"textfile.txt");
try {
BufferedWriter wr=new BufferedWriter(new FileWriter(path));
wr.write("Your Text Here");
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also you need to add following permission to your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Categories

Resources