In my application, my requirement is need to install .APK file from assets folder, so that I am trying to copy the apk file from assets folder to sdcard, I get File Not Found Exception.
these the following code:
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath();
String file_name = "ImageDownloading.apk";
AssetManager assetManager = getAssets();
try{
InputStream input = new BufferedInputStream(assetManager.open(file_name));
File path = new File(file_path);
if(!path.exists()){
path.mkdirs()
}
File file = new File(path,file_name);
OutputStream output = new FileOutputStream(file); // Here i get File Not Found Exception error.
byte data[] = new byte[1024];
int count;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch(FileNotFoundException e){
Toast.makeText(MainActivity.this,"File not found exception " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
I have spent a lot of time but i did not find out the solution.
Do you have this permission set in your manifest file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
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.
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;
}`
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"/>
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
I've developed an application in which user can download .mp3 files from server. And pre-defined a path to mnt/sdcard/foldername for saving such files. I had run my program in HTC, LG, Samsung works perfect but when I running a same program at samsung galaxy s2 getting an issue that can't able to write(store) in mnt/sdcard/foldername and tried
Environment.getExternalStorageDirectory().getAbsolutePath()
but its shows downloaded file names in given path and zero bytes for each files properties. Any idea to solve this issue?
The SG2 does usually not have a sd-card and uses the internal flash memory as "external" storage. I have solved this issue with this code:
private File initCacheDir() {
String sdState = android.os.Environment.getExternalStorageState();
File imageCacheDir;
if (sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
File sdDir = android.os.Environment.getExternalStorageDirectory();
imageCacheDir = new File(sdDir, "Android/data/" + App.PACKAGE_NAME + "/files/imageCache");
}
else
imageCacheDir = context.getCacheDir();
if(!imageCacheDir.exists())
imageCacheDir.mkdirs();
return imageCacheDir;
}
Note that this code give you the location of the cache directory, which is usually located in the Android/data folder on the sd-card.
You'll find more details how to solve this issue with SG2 here:
How could i get the correct external storage on Samsung and all other devices?
try this
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"yourfile");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
I finally found the code
public void download(String urlToDownload){
URLConnection urlConnection = null;
try{
URL url = new URL(urlToDownload);
//Opening connection of currrent url
urlConnection = url.openConnection();
urlConnection.connect();
//int lenghtOfFile = urlConnection.getContentLength();
String PATH = Environment.getExternalStorageDirectory() + "/1/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "file.mp3");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = url.openStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
System.out.println("downloaded"+urlToDownload);
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Source: link