I am downloading a file(PDF) from server using DownloadManager and request is
request.setDestinationInExternalFilesDir(this,Environment.getDataDirectory().getPath(), filename);
The File gets save in my internal storage under
"MyFiles->All files/DeviceStorage/Android/data/myPackage/files/data/"
For opening the saved file i use the following code
File sdCardRoot = new File(Environment.getDataDirectory().getPath());
if(sdCardRoot.exists()){
for (File f : sdCardRoot.listFiles()) {
if (f.isFile())
name1 = f.getName();
String path = f.getPath();
Log.e("UriFile", ""+Uri.parse(path));
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(path), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
}
But it shows document cannot be opened, But i can see the file in the location and can open it directly not from my app.
I have a SD card inserted and there is a similar folder structure created in sdcard as well .
I guess while opening the file it searches the folder on SDCARD not my internal storage, how to solve this.
Have you added permissions in AndroidManifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
As your file is stored in app internal storage i.e /data/data/packagename/ use getFilesDir() to get the path of directory holding application files & use listFiles() to get all files inside returned path directory.
getFilesDir() - Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored. No permissions are required to read or write to the returned path, since this path is internal storage.
OR you can use getExternalFilesDir(String type) to get the path of directory where you app files are saved & iterate through files using listFiles().
getExternalFilesDir(String type) - Returns the absolute path to the directory on the primary external filesystem (that is somewhere on Environment.getExternalStorageDirectory()) where the application can place persistent files it owns. These files are internal to the applications, and not typically visible to the user as media.
Usage Example:
public void listFilesInAppInternalStorage(){
//using getFilesDir()
File filesDir = getFilesDir();
File filesList[] = filesDir.listFiles();
for(File file: filesList){
Log.i(TAG, "FileName:" + file.getName());
}
//using getExternalFilesDir()
File extFilesDir = getExternalFilesDir(null);
File listOfFiles[] = extFilesDir.listFiles();
for (int i=0; i < listOfFiles.length; i++)
{
Log.v(TAG, "FileName:" + listOfFiles[i].getName());
Log.d(TAG, "FilePath:" + listOfFiles[i].getAbsolutePath());
}
}
Related
I need to create file in storage card from my Android program. I know I can create this file only in particular location like \Card\Android\data\my.application.package\. How to get this directory exact location? Code below brings path /data/my.application.package/Log and mkdirs() does not creates directories.
String path = "Log";
File root = new File(Environment.getDataDirectory().getAbsolutePath(),
"my.application.package" + File.separator + path);
boolean dirExists = true;
if (!root.exists()) {
dirExists = root.mkdirs();
}
How to get the same application path on internal storage?
You should use getFilesDir() for getting app specific internal File path and getExternalFilesDir() for getting app specific external File path.
Note that on Android 4.3 (API level 18) or lower, your app need to request storage-related permissions to access app-specific directories within external storage.
For more information see https://developer.android.com/training/data-storage/app-specific
I want to write to the physical SD card in my Android phone.
This is my code:
File sdCard = Environment.getExternalStorageDirectory();
String state = Environment.getExternalStorageState(); //shows mounted
boolean removable = Environment.isExternalStorageRemovable(); //shows false
I know that the external in getExternalStorageDirectory() not necessarily means the SD card. When I write a file to sdCard object it ends up in the internal (means build in) storage and not on the sdCard.
On my mobile I have multiple apps which write data to the sdCard, e.g. file explorer. How do they do it? I want to force to write to sdCard regardless what the manufacturer thinks is internal/external.
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");
FileOutputStream f = new FileOutputStream(file);
...
Caution: Files on external storage are not always accessible, because users can mount the external storage to a computer for use as a storage device. So if you need to store files that are critical to your app's functionality, you should instead store them on internal storage.
Request external storage permissions
To write to the public external storage, you must request the WRITE_EXTERNAL_STORAGE permission in your manifest file:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Note: If your app uses the WRITE_EXTERNAL_STORAGE permission, then it implicitly has permission to read the external storage as well.
If your app only needs to read the external storage (but not write to it), then you need to declare the READ_EXTERNAL_STORAGE permission:
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>
https://developer.android.com/training/data-storage/files.html
Now, let's say that for example you want to record a text file in your SD ...
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/your-dir-name/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, "My-File-Name.txt");
FileOutputStream os = outStream = new FileOutputStream(file);
String data = "This is the content of my file";
os.write(data.getBytes());
os.close();
The below code doesn't create a folder in my device.
String intStorageDirectory = context.getFilesDir().toString();
File folder = new File(intStorageDirectory, "test");
folder.createNewFile();;
I need a folder created for my app to store media, when user installs it. That folder should be visible on file explorer. How can i do it?
With the current snippet you created a file, you can also create folder by creating file but your current directory is the base folder, getFilesDir() points internal storage for your app which not visible nor accessible unless explicitly declared. You can create a folder and file by creating with new File().createNewFile() or create only folder using mkdirs() but you won't be able to display it using a file explorer app and that folder and files inside it will be deleted when/if user uninstalls your app.
To save files externally(This doesn't mean saving to SD Card) you can create directory and file with
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), folderName);
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs()
}
File mediaFile = new File(mediaStorageDir.getAbsolutePath() + File.separator + fileName);
And you need some kind of OutputStream to write data to that file.
Make sure that you ask <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> inside your AndroidManifest.xml file and ask write permission on runtime if your android:targetSdkVersion="23" or above
new File(context.getFielsDir(), "test").mkdirs();
createNewFile creates a file, not a folder. Using mkdirs instead of mkdir ensures that all parents exist. There's also no reason to go through a string when you already have a File.
Adding folder.mkdirs(); should work in place of folder.createNewFile(); And don't forget to add the permissions.
This will create a folder in you data directory.
And just a suggestion , if you want to store media in a SD card folder maybe Environment.getExternalStorageDirectory() is good.
I need to create a folder on my external storage (inserted SD card). I tried in several ways, but it just create a folder on device storage. I have seen to create on some android app. Please help me by providing a solution. Thanks in advance.
File directory = new File(Environment.getExternalStorageDirectory() + "/boyan/");
if (!directory.exists()) {
directory.mkdirs();
}
Permissions are:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Do it like this
File file = new File(Environment.getExternalStorageDirectory(), "Folder_name");
if (!file.exists()) {
file.mkdirs();
}
I got the solution.
Here it is.
Environment.getExternalStorageDirectory()
Above code return "/storage/sdcard0", But if you want to make a folder on external SD Card you need "/storage/sdcard1". so try to do something like this
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath().replace("0", "1") + "/boyan/");
Im trying to save data to sdCard first i tried to saave it privately within app directory on externalStorage using getExternalFilesDir but gives me nullPointerException so i tried the other way given below it worked but when i want to store files into a custom directory that i want to named myself it give me error:
FileOutputStream os;
dirName = "/mydirectory/";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)){
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + dirName);
dir.mkdirs();
//File file = new File(this.getExternalFilesDir(null), this.dirName+fileName); //this function give null pointer exception so im using other one
File file = new File(dir, dirName+fileName);
os = new FileOutputStream(file);
}else{
os = context.openFileOutput(fileName, MODE_PRIVATE);
}
resizedBitmap.compress(CompressFormat.PNG, 100, os);
os.flush();
os.close();
}catch(Exception e){
}
ErrorLog:
java.io.FileNotFoundException: /mnt/sdcard/mvc/mvc/myfile2.png (No such file or directory)
Your directory "/mnt/sdcard/mvc/mvc" may not exist. What about changing your path to store the image in the Environment.getExternalStorageDirectory() path and then working from there?
Also, as Robert pointed out, make sure you have write permission to external storage in your manifest.
Edit - to create directories:
String root = Environment.getExternalStorageDirectory().toString();
new File(root + "/mvc/mvc").mkdirs();
Then you can save a file to root + "/mvc/mvc/foo.png".
Have you requested permission to write onto SD card? Add the following string to you app manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should check if you have added the required permission android.permission-group.STORAGE to your app. Without that permission you won't be able to access anything on the SD-Card.
BTW: On the Android system I know the SD-card is mounted on /sdcard not /mnt/sdcard
I found this book to be very helpful: "Pro Android Media: Developing Graphics, Music, Video, and Rich Media Apps for Smartphones and Tablets". I noticed a part that allows saving images and stuff to the SD card.