Saving file in sd card without extension and access that with extension - android

I am downloading a pdf file from server and saving it on sd card without extension (for security purpose so that normal user can't open that file from file manager).For e.g.- I am downloading abc.pdf and saving it on sd card with abc on below path
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "files");
And later I want to view that file by adding extension.
So when I am accessing that file from code by using below code then its gives error file does't exist..
String s=Environment.getExternalStorageDirectory() + "/files/" + "abc";
File pdfFile = new File(s+".pdf");
So how can I save file in sd card without extension and later open that file with extension.

Workaround for your problem is to rename your saved pdf file without extension to filename with .pdf extension & after completing/accessing view or read operation on your new pdf extension file again you can rename it to file without extension
Example Usage:
String currentFileName = Environment.getExternalStorageDirectory() + File.separator
+ "files" + File.separator + "abc";
String renamedFilename = currentFileName + ".pdf";
boolean isRenamed = renameFile(currentFileName, renamedFilename);
Log.d("isRenamed: ", "" + isRenamed);
if(isRenamed {
//perform your operation
}
Again rename the file if not in use (here exchange renameFile() parameters):
boolean renameAfterOperation = renameFile(renamedFilename, currentFileName);
Log.d("renameAfterOperation : ", "" + renameAfterOperation );
And here is renameFile(currentFilePath, renamedFilePath):
public boolean renameFile(String currentFilePath, String renamedFilePath){
File currentFile = new File(currentFilePath);
File newFile = new File(renamedFilePath);
boolean isrenamed = currentFile.renameTo(newFile);
return isrenamed;
}
In this way whenever you want to perform operation on saved file first rename it to .pdf & whenever it's not in use, again rename it without extension. Let me know if this works for you..

Related

Check If File Exists Before downloading the file

I am using download manager to download the file. The code for downloading the file is as follow.
private String DownloadData(Uri uri, View v, String textview) {
long downloadReference;
// Create request for android download manager
dm = (DownloadManager)getContext().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
//Setting title of request
request.setTitle(textview);
//Setting description of request
request.setDescription("Android Data download using DownloadManager.");
//Set the local destination for the downloaded file to a path within the application's external files directory
request.setDestinationInExternalFilesDir(getContext(), DIRECTORY_DOWNLOADS, File.separator + "Dr_Israr_Ahmad" + File.separator + textview+".mp3");
//Enqueue download and save into referenceId
downloadReference = dm.enqueue(request);
return null
}
The above code works fine. What i need to do now is if the file is already downloaded than i want my app to play it. The code which is used is
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3"));
File file = new File(path);
if(file.exists()){
Toast.makeText(getContext(),path+ "/n exists", Toast.LENGTH_SHORT).show();
} else if (!file.exists()) {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("http://www.digitalsguide.com/mobile-apps/dr-israr-ahmad/audios/"+filename+".mp3");
String filepath = DownloadData(uri,view,filename);
}
but the problem is the condition is true even if the file doesn't exist. Is there a problem in my path ? kindly help me out,
I detected some strange behavior with exists time ago and changed it to isFile:
File file = new File(path);
if (file.isFile()) {
Toast.makeText(getContext(), path + "/n exists", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Downloading", Toast.LENGTH_SHORT).show();
// ...
}
I think the mobile, somehow, created a directory every time new File() was executed.
Check this.
Because getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) returns /storage/emulated/0/Android/data/<PACKAGE_ID>/files/Download. It's not the folder where DownloadManager downloads files when we set Environment.DIRECTORY_DOWNLOADS.
Try to put your path like the example shown below:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ "/" +filename);
Here filename is example.pdf
you can then check if file exists or not
.getExternalFilesDir(yourFilePath) creates a directory in your code. so use it like this.
String path = String.valueOf(getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)+ File.separator+"Dr_Israr_Ahmad" + File.separator +filename+".mp3");

Save Java.io.File to Android FileSystem on KitKat and above

I'm working on an app that saves thermal images from a FLIR camera to the SD Card on the phone.
I'm using Android Marshmallow and I have to use the FLIR SDK.
In the FLIR SDK is a class "Frame". The class has a method "Frame.save", that needs a Java.io.File to save a thermal image: This is from the documentation:
public void save(java.io.File file,
RenderedImage.Palette previewPalette,
RenderedImage.ImageType previewImageType)
throws java.io.IOException,
java.lang.IllegalArgumentException
Saves a thermal JPEG file, which has a rendered visual preview and embedded thermal data
When I understand it right, on KitKat or higher I have to use the Storage Accsess Framework. So I used it. Send a Intent and get back a Uri to a picked folder on the SD Card. Now to the tricky part. This funktion should create a File and return a Java.io.File that ready for the "Frame.save" method.
public File getJavaFile (String Name, Uri myUri) {
DocumentFile pickedDir = DocumentFile.fromTreeUri(context, myUri); // Document file aus URI
DocumentFile DocumentFile = pickedDir.createFile("image/plain", Name + ".jpg" );
File file = new File(DocumentFile.getUri().getPath());
if(file.canWrite()){
Log.d(TAG + "/getJavaFile", "File can write");
}else {
Log.e(TAG + "/getJavaFile", "File cannot write");
}
Log.d(TAG + "/getJavaFile:", "File Created:" + file.getPath());
return file;
}
The file that the function return is not readable or writeable...
Otherwise, when I try to create a File directly, like so:
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/saved_images");
Log.d(TAG, file.getPath());
Then the the system always gives me this emulated folder:
E/MainActivity: /storage/emulated/0/saved_images
So the question is: How to get a useable Java File, thats stored on the public storage space... Thank you for your time!

Creating new file from assets folder, isDirectory() returns false

When I call this :
File directory = new File("file:///android_asset/");
then this :
directory.isDirectory()
Always returns false.
Am I doing something wrong here ?
(Sorry if it is a dumb question)
Edit:
I store several images in the assets folder and I wanted to load them in my app (like an image gallery).
Call
directory.mkdirs();
after you created the File object
Edit:
in your case try to change file url as below:
new File("/mnt/external_sd/");
or find the true path by looking it in eclipse File explorer.. do not start it with file://
May be you are searching for this:
String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();

unable to give a path to DownloadManager

i would download with DownloadManager a file in a specific directory. At the beginning of my app, i create (if doesn't exist) a folder:
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
externalStorageWriteable = true;
directory_path = Environment.getExternalStorageDirectory()
+ "/" + context.getResources().getString(R.string.app_name);
directory = new File(directory_path);
if (!directory.exists()) {
directory.mkdirs();
}
}
if i check with a filemanager, folder it's available at /sdcard/folderName but if i print on logcat directory_path variable, i obtain
/storage/emulated/0/folderName
I try to download file by passing destination folder like
Uri destination = Uri.fromFile(new File(directory_path));
request.setDestinationUri(destination);
//request is of type DownloadManager.Request
but when i check where file it's stored, my folder is empty and downloaded file is stored inside /sdcard/Download
Could someone tell me why and how can i solve this issue?
Add .toString()
Environment.getExternalStorageDirectory().toString()

Move Images to gallery programmatically in Android

This question may have been asked elsewhere but did not work for me.
I save images in the app-private folder and the user has the option to move it to Android gallery. So my question is how to do that?
This is my code
String outPath = "new path which is gallery";
File outFile = new File(outPath);
// File (or directory) to be String
sourcePath="image in the app-private folder";
File file = new File(sourcePath);
// Destination directory
boolean success = file.renameTo(new File(outFile, "name of image"));
System.out.println("success: "+success);
success here is always "false"

Categories

Resources