Java - Getting specific folder and files from zip file - java

So I am working on an Android app and what I am trying to do is make it so a user selects a zip file, it extracts the contents of it into an apk and installs the modified APK for the user. Right now all the files in the zip file have to be in the root of the zip file for it to work, if there is a directory and than the files I need it will not work. I am trying to make it scan for, for example the 'assets' folder and than get the directory its located in and copy all the files from that directory. I've tried extracting the files first and scanning using a loop, and for some reason had no success doing that, and it was time consuming anyways. If you know any libraries or could point me in the right direction that would be great! Thanks!

BTW you can extract all the files from zip folder like below. i.e
private String unpackZip(String path, String zipname) {
String apkfilename = "";
InputStream is;
ZipInputStream zis;
try {
String filename;
is = new FileInputStream(path + "/" + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + "/" + filename);
fmd.mkdirs();
continue;
}
// This condition is to only extract the apk file
if (filename.endsWith(".apk")) {
apkfilename = filename;
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 apkfilename;
}
return apkfilename;
}
//To install the apk file call the method
String apkfilename=unpackZip(Environment.getExternalStorageDirectory()
.getPath(), "temp.zip");
try {
File file = new File(Environment.getExternalStorageDirectory()
.getPath(), apkfilename);
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(
Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(promptInstall);
} catch (Exception e) {
e.printStackTrace();
}
//Also add the read write permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Related

Unzipping Multipart file with and without subdirectories

Unzipping multipart file with and without subdirectories since I am not giving any instruction to user to how to zip the file therefore I need to find/search all files from Zip file which might have directories and subdirectories and keeping all files in a seperate different folder.
So basically it is some kind of smart unzipping where it detects the directory using ZipEntry then skip and find file to write in the folder.
I have written a code but I am not even near it since I am getting only one file that too which has no directories in it.
String outputPath="C:\\Users\\Plootus\\exceldocs\\";
FileSystem fileSystem = FileSystems.getDefault();
try
{
ZipInputStream zis=new ZipInputStream(serverFile.getInputStream());
BufferedInputStream bis=null;
InputStream is=null;
//Get file entries
ZipEntry entry=null;
//We will unzip files in this folder
while ( (entry = zis.getNextEntry()) != null ) {
System.out.println(entry.getName());
if(!entry.isDirectory()) {
System.out.println(entry.getName());
is = zis;
bis = new BufferedInputStream(is);
String uncompressedFileName = outputPath+toolName+entry.getName();
Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
Files.createFile(uncompressedFilePath);
FileOutputStream fileOutput = new FileOutputStream(uncompressedFileName);
while (bis.available() > 0)
{
fileOutput.write(bis.read());
}
fileOutput.close();
System.out.println("Written :" + entry.getName());
bis.close();
is.close();
}
}
zis.close();
return true;
}
catch(IOException e)
{
return false;
}
return false;
Objective: Zip file contains possible entries
1.) abc.zip(Multipart File)
-folder1-arkan.csv,dan.csv,kud.csv
abc.zip(Mutlipart File)
-folder1--bio.csv(file)-folder-2(inside folder1)-arkan.csv,dan.csv,kud.csv
abc.zip(Mutlipart File)
-arkan.csv,dan.csv,kud.csv
Instead of extracting from MultipartFile and handling entries as ZipEntry(as told by #Jokkeri) is not possible therefore I found other way to do it.
I will save that file and when the operation is done then delete it.
After receiving multipart file I saved the file using File object(saveZip)
try(ZipFile file = new ZipFile(saveZip.getCanonicalPath()))
{
FileSystem fileSystem = FileSystems.getDefault();
//Get file entries
Path inputpath=fileSystem.getPath(file.getName());
Enumeration<? extends ZipEntry> entries = file.entries();
//We will unzip files in this folder
File directory=new File(zipFilePath.concat(username+"-"+toolName));
if(!directory.exists()) {
directory.mkdir();
}
//Iterate over entries
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
String abc[]=entry.getName().split("/");
//Else create the file
if(!entry.isDirectory())
{
InputStream is = file.getInputStream(entry);
BufferedInputStream bis = new BufferedInputStream(is);
String uncompressedFileName = zipFilePath +username+"-"+toolName+"/"+ abc[abc.length-1];
Path uncompressedFilePath = fileSystem.getPath(uncompressedFileName);
if(Files.notExists(uncompressedFilePath))
Files.createFile(uncompressedFilePath);
FileOutputStream fileOutput = new FileOutputStream(uncompressedFileName);
while (bis.available() > 0)
{
fileOutput.write(bis.read());
}
fileOutput.close();
System.out.println("Written :" + entry.getName());
is.close();
bis.close();
}
}
file.close();
Files.deleteIfExists(inputpath);
return true;
}catch(IOException e)
{
e.printStackTrace();
return false;
}

How to compress a folder and send via email in android

Everyone: I am trying to send a folder (there are many files inside this folder) via email in Android Development.
First, I tried send the whole folder directly by using a click event and intent event.
My first attempt code shows the following:
My first part of code is onclicklistener event:
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu,int index) {
switch (index) {
case 0:
sendEmail(list.get(position).getName());
break;
case 1:
list.remove(position);
adapter.notifyDataSetChanged();
}
return false;
}
});
My second code to send Email is as follows:
public void sendEmail(String data_path){
Intent email = new Intent(Intent.ACTION_SEND);
File file_location = new File(SDCard, data_path);
email.setType("vnd.android.cursor.dir/email");
email.putExtra(Intent.EXTRA_EMAIL, new String[]{"example#gmail.com"}); //set up email
email.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file_location)); //add attachment
email.putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(email, "pick an Email provider"));
}
When I run this code, it works fine to jump into email sender, but without any folder implement, the email implement is empty.
I am wondering if it is impossible to send a folder directly via email.
Now I am trying to another way to solve this: I am planning to compress folder(.zip) first and then send the zip file to email in just one click event, But I can not find any solutions showing how to compress the folder and send zip file in just one click event, What I mean is that I want a solution which:
Clicks the file that needs to be sent (click event has finished)
After it triggers the click event, the app will compress the clicked file to a zip file.
The zip file will automatically add as mail implements that waits to be sent
I was trapped there for many days and still failed to find any answers, I also search on StackOverflow, but most questions are about how to compress a file or send file by email. I am looking for a way to compress a folder and send a zip file in one click event.
If you have any ideas, I would quite appreciate them!
Here is a workaround to transform your folder into zip.
First, grant permissions:
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And then use this to transform your folder:
/*
*
* 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));
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;
}
Here is another example:
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());
}
}
Also you can use this library to zip a folder or file.
Import the .jar into your project and then you can do this to transform what you need:
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));
}
This should do the trick.

Android file storage

I have a zip file in assets. On first run of app, zip file (all files and folders) gets unzipped and stored in internal storage area. The base unzipped path is getFilesDir(). Since zip also contains folders, i could not use openFileOutput as it gave an error, contains a path separator. So i have used FileOutputStream instead which is now working fine. Since FileOutputStream does not expect private flag. Are these unzipped files and folders are private to my app or can they be accessed from other apps?
Here's the code,
`public boolean unpackZip(InputStream is, String path) throws IOException {
String filename;
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
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();
return true;
}`

How To Copy File From SD to Local Storage on Android

I know with Kit Kat you can only write to your applications package specific directory on SD Cards. I was however under the impression you could still copy files from an SD card to local storage with the:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I am simply testing if I can copy one file. If I am able to do that I will add the code to search the entire SD card DCIM folder. For now I have the following code (please forgive the messiness of the code, I have written C# and vb.net but java is still very new to me):
String dirPath = getFilesDir().getAbsolutePath() + File.separator + "TCM";
File projDir = new File(dirPath);
if (!projDir.exists())
projDir.mkdirs();
String CamPath = projDir + File.separator + tv2.getText();
File projDir2 = new File(CamPath);
if (!projDir2.exists())
projDir2.mkdirs();
File LocalBuck = new File(projDir2 + File.separator );
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath();
File directory1 = new File (sdCard.getAbsolutePath() + "/DCIM");
File directory = new File(directory1 + "/100SDCIM");
File Buckfile = new File(directory, "/BigBuck.jpg");
try {
exportFile(Buckfile, LocalBuck);
} catch (IOException e) {
e.printStackTrace();
}
Here is my code for the export function/application:
private File exportFile(File src, File dst) throws IOException {
//if folder does not exist
if (!dst.exists()) {
if (!dst.mkdir()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HHmmss").format(new Date());
File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
//Straight to Error Handler
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(expFile).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
return expFile;
}
Here is what my emulator looks like:
Looking for: Debug of SD Location
Should Find It?: EmulatorShowingSd
Question: Am I even able to copy a file from the SD card to local storage after KitKat; if so what is wrong in the code causing the exception to be thrown when it tries to access the SD card file?

I keep getting java.io.FileNotFoundException with my zip extractor

Could anybody help me with my java zip extractor as stated in the title I keep getting java.io.FileNotFoundException on the folders with files in them
public void UnZip() {
try {
byte[] data = new byte[1000];
int byteRead;
BufferedOutputStream bout = null;
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(sourceFile)));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
String filename = entry.getName();
File newfile = new File(Deobf2 + File.separator + filename);
System.out.println("file unzip : " + newfile.getAbsoluteFile());
new File(newfile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newfile);
int len;
while ((len = zin.read(data)) > 0) {
fos.write(data, 0, len);
}
fos.close();
entry = zin.getNextEntry();
}
zin.closeEntry();
zin.close();
System.out.println("Done");
} catch (Exception e) {
e.printStackTrace();
}
}
error log
http://pastebin.com/crMKaa37
values
static String tempDir = System.getProperty("java.io.tmpdir");
public static File Deobf = new File(tempDir + "Deobf");
public static String Deobf2 = Deobf.toString();
entire code paste
http://pastebin.com/1vTfABR1
I have copy pasted same code and it is working fine. I think u dont have administrator permission on C drive. login As Administrator and run . it will work.
Access Denied Exception will come when u don have administrator level of permission on C drive.
The problem is Your doing
String Deobf2 = Deobf.toString();//this does not give the location of the file
use
file.getAbsolutePath();
in your case Deobf.getAbsolutePath();
instead. Check http://www.mkyong.com/java/how-to-get-the-filepath-of-a-file-in-java/
if you want to get the path only till the parent directory check this How to get absolute path of directory of a file?
Problem fixed changed some code
for anyone whos wants a copy of the working zip extraction code here you go http://pastebin.com/bXL8pUSg
The variable Deobf2 in the output of the zip

Categories