I tried a simple file write program in Android.
try
{
//File f1=new File("/sdcard/Prag.txt");
File f1=new File("J:\\Prag.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f1,true));
out.write("Pragadheesh" + "\n");
out.close();
} catch (IOException ioe)
{ioe.printStackTrace();}
But the exception is getting hit. How can I fix this?
[edit]:
I tried File f1=new File(Environment.getExternalStorageDirectory() + "//Prag.txt");
and f1 value = /mnt/sdcard/Prag.txt
But still the exception gets hit. I have changed the permission too in manifest file
[solution]
As per Krishnabhadra's reply, I had to Make sure your SDCard is not mounted on a PC
Android is based on linux so windows style paths like "J:\\prag.txt" won't work. In linux paths are like this: "/folder1/folder2/file.txt"
Also don't use hardcoded paths, because different phones might have different path for the SD card. Therefore you you should use Environment.getExternalStorageDirectory() that gives the path to the SD card programmatically.
So use:
File f1=new File(Environment.getExternalStorageDirectory() + "Prag.txt");
Also add necessary permission by:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Inside your manifest, somewhere outside application tag.
All the above answers are useful..But remember one more thing..Make sure your SDCard is not mounted on a PC. Only one device can access SDCard at one time. ie either the computer or the phone can access the SD card, but not both at the same time..If it is mounted on PC then your code won't work..See this thread
Replace:
File f1=new File("J:\\Prag.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(f1,true));
with:
BufferedWriter out = new BufferedWriter(new FileWriter(Environment.getExternalStorageDirectory(),"prag.txt"))
Have you set the required permission in your manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
what is this path "J:\Prag.txt" ; Android doesn't recognize any drive path like system.
Use sdcard path for it.
File f1=new File(Environment.getExternalStorageDirectory()+"/Prag.txt");
Also mention permission in manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
I tried a lot to find a solution but everything has failed so far. It's probably something stupid.
I'm trying to save a photo as a jpeg in the storage of the phone. Everything fails even the simple task of making a folder. The code below is what I use to create the folder.
private void makeFolder(){
try{
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),getString(R.string.app_name));
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
Toast.makeText(this,"Done",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"folder_failed",Toast.LENGTH_SHORT).show();
System.out.println(folder.getAbsolutePath());
}
}catch (Exception e){
Toast.makeText(this,"exception",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
I have tried many different ways like:
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + getString(R.string.app_name)+File.separator);
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + getString(R.string.app_name);
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
,getString(R.string.app_name));
I have tried both mkdirs and mkdir and
-Environment.getExternalStorageDirectory().getAbsolutePath()
-getExternalStorageDirectory().getAbsolutePath()
-Environment.getExternalStorageDirectory()
-getExternalStorageDirectory()
The permission exists in the manifest and is accepted.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The path the the System.out prints is "/storage/emulated/0/appname"
I don't know what else to try. Similar code works for other applications. Min API is 23.
Any help is much appreciated.
I suggest you to try Context.getExternalFilesDir() instead of Environment.getExternalStorageDirectory()
If your test device runs Android 10/Q or API Level 29+: there are a few permission changes with storing data to media folder. You can store your data without problems to your app folder, but if you remove the app the images are gone too.
The easiest way is to add android:requestLegacyExternalStorage="true" in the manifest under application but it is more like a work around and it will probably not be supported for long.
Search for "store image android 10" here and you find the right way for you.
Below is my sdcard path of a start.mp4 file. I am able to get this file in read mode but not able to open in rw mode. I have given runtime permissions also. It throws a exception:
/storage/3263-6232/piyush/Download/start.mp4: open failed: EACCES (Permission denied)
Code:
String sdCardPath = "/storage/3263-6232/piyush/Download/start.mp4";
File file = new File(sdCardPath );
try{
RandomAccessFile rfs = new RandomAccessFile(file, "rw");
rfs.seek(file.length());
rfs.close();
} catch (IOException e) {
e.printStackTrace();
}
In the above code I have taken sdcardpath to a file which exists in sdcard.
Than after that whenever I tried to open that file in outputstream using RandomAccessFile it gives FilenotFound Exception:
/storage/3263-6232/piyush/Download/start.mp4: open failed: EACCES (Permission denied)
Does your Manifest looks like this?
The uses-permission tag needs to be outside the application tag
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<application>
...
<activity>
...
</activity>
</application>
</manifest>
PS: If you are using Post M device for testing then make sure you ask WRITE_EXTERNAL_STORAGE permission before doing any operation on you file.
Change your Storage location to /storage/3263-6232/Android/data/<Your package Name>/files will solve your issue
Above Path is only have write access for related third party apps, elsewhere you can read the file but can't write new file.
Or you need to apply Storage Access Framework for getting write permission.
For more details you can visit
https://developer.android.com/guide/topics/providers/document-provider.html
How can i get extSdcard path in android?
There are 2 storage, first external storage in which all the phones have it but there is second storage which is called removable storage (micro sdcard).
I want to get the path to the micro sdcard in android, how is that possible?
Starting from KitKat, you have access to a method to get that directory :
Context.getExternalFilesDirs()
Note that it may return null if the SD card is not mounted or moved during the access. Also, you might need to add these permissions to your manifest file :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Apparently some users had trouble with this method, not returning the SD card path. I found some useful informations on how it can works and how it can not depending on the device on this post.
Check this https://developer.android.com/guide/topics/data/data-storage.html#filesExternal for complete reference as you need to define permission to read and write to the external SD also there is code in the above link which checks if SD card is available before performing any action
The following works for me!
File[] Dirs = ContextCompat.getExternalFilesDirs(this.getApplicationContext(), null);
File path = (Dirs[1]);
String pathSD = Dirs[1].toString();
int firstOpen = pathSD.indexOf("/");
int secondOpen = pathSD.indexOf("/", firstOpen + 1);
int thirdOpen = pathSD.indexOf("/", secondOpen + 1);
String filename = pathSD.substring(firstOpen, thirdOpen + 1);
path = new File(filename);
As of API level 24, you can use the StorageManager class:
https://developer.android.com/reference/android/os/storage/StorageManager#getStorageVolumes()
I am trying to access WhatsApp database folder exists in Environment.getExternalStorageDirectory().getAbsolutePath() + /WhatsApp/Databases location in un-rooted device.
My aim is to collect these files and decrypt them and show each messages to Web portal. Here is the code to collect these files:
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + location;
f = new File(path);
final File file[]=f.listFiles();
final int size = file.length;
Whenever i am running on rooted device, It is working but on some unrooted devices it is throwing nullpointer because it is not able to get the list of all database files.
My question is: Is it possible to ready WhatsApp Database files when device is not root?
or is there any way to do it?
I am not sure the root effects. Have you get the PERMISSION for your app ? if not, you can try to put uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE on your manifest and then test it.
you are able to read database file try below code its worked if device is not rooted.
i have tried these in Samsung Grand 2, HTC
String path = Environment.getExternalStorageDirectory()
+ "/WhatsApp/Databases";
File file = new File(path);
if (file.exists()) {
File[] filenames = file.listFiles();
for (File tmpf : filenames) {
// Do something with the files
if (tmpf.isFile()) {
Log.e("tmpf-------->", "not add---->" + tmpf.getPath());
}
}
} else {
Log.e("folder not found", "folder not found");
}
don't forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
No, You can't get SQLite databse file from an Android device if it's not rooted, since you have no permission to access data folder.
But yes you can get database if you run app on emulator.
Im trying to build a directory called "images" on the SD card on android. This is my code but its not working? Can anyone give me some advice?
File picDirectory = new File("mnt/sdcard/images");
picDirectory.mkdirs();
Update: Since Android 10,11 Storage updates, Google has restricted Storage access through standard programming language file operations.
For applications targeting only Android 10 (API 29) and above, you need to declare "requestLegacyExternalStorage="true" " in your android manifest file to use programming language based file operations.
<application
android:requestLegacyExternalStorage="true"
....>
==========
You want to be sure you are correctly finding the address of your SDCard, you can't be sure its always at any particular address. You will want to do the following!
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"images");
directory.mkdirs();
Let me know if this works for you!
You will also need the following line in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I use this to know the result:
File yourAppDir = new File(Environment.getExternalStorageDirectory()+File.separator+"yourAppDir");
if(!yourAppDir.exists() && !yourAppDir.isDirectory())
{
// create empty directory
if (yourAppDir.mkdirs())
{
Log.i("CreateDir","App dir created");
}
else
{
Log.w("CreateDir","Unable to create app dir!");
}
}
else
{
Log.i("CreateDir","App dir already exists");
}
you can use this :
File directory = new File(Environment.getExternalStorageDirectory() + "/images");
directory.mkdirs();
Environment.getExternalStorageDirectory() is deprecated. So you should use this:
File directory = new File(this.getExternalFilesDir(null).getAbsolutePath() + "/YourDirectoryName");
directory.mkdirs();
One thing that is worth noting is if you always get false from the mkdirs(), try to unplug your device from pc, and see if it could create folders. At least I tried, it worked for me, currently I'm looking for ways to fix this problem.
To create specific root directory and its sub folder i use this code
String root = Environment.getExternalStorageDirectory().toString();//get external storage
File myDir = new File(root + "/grocery"+"/photo/technostark");//create directory and subfolder
File dir=new File(root + "/grocery"+"/data");//create subfolder
myDir.mkdirs();
dir.mkdirs();
To create file inside sd card you have to use Environment.getExternalStorageDirectory()
/**
* Creates a new directory inside external storage if not already exist.
*
* #param name The directory name
*/
public static void createNewDirectory(String name) {
// create a directory before creating a new file inside it.
File directory = new File(Environment.getExternalStorageDirectory(), name);
if (!directory.exists()) {
directory.mkdirs();
}
}
Following two important parameter which helps you to create directory
1. directory.mkdirs() :
Creates the directory named by this file, creating missing parent
directories if necessary.
2. directory.mkdir() :
Creates the directory named by this file, assuming its parents exist.
For more you can how getExternalStorageDirectory() works please see link
This should help.
First get the path of the external storage:
File root=Environment.getExternalStorageDirectory();
Then:
File picDirectory = new File(root.getAbsolutePath(), "mnt/sdcard/images");
picDirectory.mkdirs();