file.delete() from android internal storage return false - android

I have a method to download a image from url and save it in a folder at Internal storage
public void saveDynamicImage(String url,String fileName, String folderName) {
InputStream iStream;
BufferedInputStream buffInputStream;
ByteArrayBuffer byteArray = null;
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
iStream = httpResponse.getEntity().getContent();
buffInputStream = new BufferedInputStream(iStream, 8 * 1024);
byteArray = new ByteArrayBuffer(50);
int current = 0;
while ((current = buffInputStream.read()) != -1) {
byteArray.append((byte) current);
}
} catch (ClientProtocolException e1) {
} catch (IOException e1) {
}
File dynamicImageDir = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_PRIVATE);
File appNamefileDir = new File(dynamicImageDir, BaseActivity.appDataStore.getAppName());
appNamefileDir.mkdirs();
File controlNameDir = new File(appNamefileDir, folderName);
controlNameDir.mkdirs();
File file = new File(controlNameDir, fileName);
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(byteArray.toByteArray());
outputStream.close();
System.out.println("DynamicImage saving over!..");
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
i want to delete the whole directory at a point of time. My method to delete entire directory is
public void deleteDynamicImage() throws NullPointerException,FileNotFoundException {
File rootDirectory = context.getDir(AppConstants.DYNAMIC_IMAGE, Context.MODE_WORLD_WRITEABLE);
boolean status = rootDirectory.delete();
Log.e("", "delete : "+status);
}
i am getting the status as 'false'. files are created and working fine. only problem in deletion. Is there any thing I am missing?

Is your file a directory?
If it's, you need to delete file in this folder first
this code is work well
public void deleteDirectory(File file) {
if( file.exists() ) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for(int i=0; i<files.length; i++) {
if(files[i].isDirectory()) {
deleteDirectory(files[i]);
}
else {
files[i].delete();
}
}
}
file.delete();
}
}

To delete Directory use this:
public void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) for (File child : fileOrDirectory.listFiles())
DeleteRecursive(child);
fileOrDirectory.delete();
}

How to delete File in Android:
public void deleteFile(String filePath){
if(filePath.startsWith("content://")){
ContentResolver contentResolver = getActivity().getContentResolver();
contentResolver.delete(Uri.parse(filePath), null, null);
}else {
File file = new File(filePath);
if(file.exists()) {
if (file.delete()) {
Log.e(TAG, "File deleted.");
}else {
Log.e(TAG, "Failed to delete file!");
}
}else {
Log.e(TAG, "File not exist!");
}
}
}
Important Note:
if you get file path from Uri [Don't use Uri.toString()] as it will return file path in file:/// format, in this case [new File(filePath)] will not work. So to get file path always use Uri.getPath().

You are trying to delete a directory. File.delete() works on directory only if this is empty

Related

okhttp not downloading the file

I am using okhttp for downloading video from server. there is no error no exception but the file is not downloading every where but it seems as it is.
Here is the code:
OkHttpClient httpClient = new OkHttpClient();
Call call = httpClient.newCall(new Request.Builder().url("http://res.cloudinary.com/demo/video/upload/v1427018743/ygzxwxmflekucvqcrb8c.mp4").get().build());
try {
File file = new File(getCacheDir(), user_Videos.get(i).video_title+ ".mp4");
OutputStream out = new FileOutputStream(file);
Response response = call.execute();
if (response.code() == 200) {
InputStream inputStream = null;
try {
inputStream = response.body().byteStream();
byte[] buff = new byte[1024 * 8];
long downloaded = 0;
long target = response.body().contentLength();
publishProgress(0L, target);
while (true) {
int readed = inputStream.read(buff);
if (readed == -1) {
break;
}
//write buff
downloaded += readed;
try {
out.write(buff,0,readed);
} catch (Exception e) {
e.printStackTrace();
}
publishProgress(downloaded, target);
if (isCancelled()) {
return false;
}
}
return downloaded == target;
} catch (IOException ignore) {
return false;
} finally {
if (inputStream != null) {
out.flush();
out.close();
inputStream.close();
}
}
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
The progress is showing correctly but video is not showing in directory.
Thanks.
So there is no problem in my code but the path. Thanks #greenapps who made me think about path/ directory.
Basically I just change the path to a real one instead of cache and yup here is the video.
Changed this line
File file = new File(getCacheDir(), user_Videos.get(i).video_title + ".mp4");
to this
File file = new File(Environment.getExternalStorageDirectory(), user_Videos.get(i).video_title+ ".mp4");
Thanks #greenapps for the clue.

Problems creating PDF from stream

I am receiving a stream from the server. That stream represents a PDF, and I KNOW it is a pdf file. I am receiving it, and storing in the phone this way:
ResponseBody body=response.body();
File dir = new File(Environment.getExternalStorageDirectory() + “/myApp/“+variable+"/“+anotherVariable);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, objetoFichero.get("nombre").getAsString());
try {
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
InputStream is = body.byteStream();
int len = 0;
byte[] buffer = new byte[1024];
while((len = is.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
fos.flush();
fos.close();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This way, the file is created, but using a file browser I try to open the pdf, and it opens, but it is blank.
Any idea about what I am doing wrong?
Thank you.
Assuming you have the document (the pdf) as a byteArray (documentBytes)
I would:
createUri(this, new File(getCacheDir(), "pdf/whateverNameYouWant.pdf"), documentBytes)
public static Uri createUri(#NonNull final Context context, final File name, #NonNull final byte[] data) throws IOException {
final File parent = name.getParentFile();
if (!parent.exists()) {
FileUtils.mkdirs(parent, null);
}
final OutputStream out = new FileOutputStream(name);
try {
out.write(data);
} finally {
StreamUtils.closeSilently(out);
}
return createUri(context, name);
}
public static void mkdirs(final File dir) {
if (!dir.mkdirs()) {
Log.w("File", "Failed to mkdirs: " + dir);
}
}
public static void closeSilently(#Nullable final Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (final Throwable ignore) {
}
}
}
You can then show the document with the uri received by createUri()

Copying file from asset folder to sdcard doesn't seem to work

I am trying to copy an image from the asset folder to the sdcard but doesn't seem to copy it on first launch. It creates the folder okay but doesn't copy the file over.
prefs = getPreferences(Context.MODE_PRIVATE);
if (prefs.getBoolean("firstLaunch", true)) {
prefs.edit().putBoolean("firstLaunch", false).commit();
File nfile=new File(Environment.getExternalStorageDirectory()+"/My Images");
nfile.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("middle.jpg");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images" + filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
private void copyFile(InputStream in, OutputStream out) {
// TODO Auto-generated method stub
}
middle.jpg is the file i want to copy over. Can any one tell me what i am doing wrong?
PS i have WRITE_EXTERNAL_STORAGE in my manifest.
Thanks
You forgot to add / in the end of /My images while constructing the path
File outFile = new File(Environment.getExternalStorageDirectory()+ "/My Images/" + filename);
out = new FileOutputStream(outFile);
because the filename would be MyImages+Filename so it wouldn't exists for copying.

How to Copy the Internal Default ringtones to External Memory in Android

Please help me out I am not getting the default ringtone file path.
Can any body tell how to get access to the default ringtone in Android. Here is my code for doing that thing. I have commented the path that I gave directly to asset manager to open the file and read it.
public void copyAssets() {
AssetManager assetManager = this.getAssets();
// String FileName="//media/internal/audio/media/";
File io=getFilesDir();
String[] files = null;
try {
files = assetManager.list("");
// files=assetManager.list(FileName);
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
// File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal dir;
// File fileWithinMyDir = new File(mydir, "myfile"); //Getting a file within the dir.
// FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual
//
try {
in = assetManager.open("Ringtone");
// File myFolder = new File(Environment.getDataDirectory() + "/myFolder");
File myFolder = this.getDir("myFolder", this.MODE_PRIVATE);
File fileWithinMyDir=new File(myFolder,"Ringtoness");
out = new FileOutputStream(fileWithinMyDir);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
}
}
public void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}`

Download all types of file from Dropbox

I am working on Dropbox. I see the documentation. This is my code to display list:
Entry entryCheck = mApi.metadata("/", 100, null, true, null);
Log.i("Item Name", entryCheck.fileName());
Log.i("Is Folder", String.valueOf(entryCheck.isDir));
I got all list from dropbox but my question is that
Here entryCheck.isDir always give me true value if it is file or directory so how i can know which is file or which one is directory?
How i downloaded that files.
I tried with this but it is not working:
private boolean downloadDropboxFile(String dbPath, File localFile,
DropboxAPI<?> api) throws IOException {
BufferedInputStream br = null;
BufferedOutputStream bw = null;
try {
if (!localFile.exists()) {
localFile.createNewFile(); // otherwise dropbox client will fail
// silently
}
DropboxInputStream fin = mApi.getFileStream("dropbox", dbPath);
br = new BufferedInputStream(fin);
bw = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int read;
while (true) {
read = br.read(buffer);
if (read <= 0) {
break;
}
bw.write(buffer, 0, read);
}
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// in finally block:
if (bw != null) {
bw.close();
}
if (br != null) {
br.close();
}
}
return true;
}
This will work
String inPath ="mnt/sdcard/"+filename;
File file=new File(inPath);
try {
mFos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
mErrorMsg = "Couldn't create a local file to store the image";
return false;
}
mApi.getFile("/"+filename, null, mFos, null);
This downloads the file and store it in the sdcard location inPath.
You have to do it in a new thread,not in main thread.Use AsyncTask.
http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html
this link explains why..

Categories

Resources