how to read and write file on android 4.4? - android

I need to open gallery to show images in a specific directory,after a search I follow this
How to open gallery to show images in a specific directory
but the file.list returns me a null String[] on android 4.4
Than I write some test code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listDirectory("ExternalStorageRoot",
Environment.getExternalStorageDirectory());
listDirectory(
"DCIM",
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
writeFileTest();
}
private void writeFileTest() {
String tag = "WriteTest";
String path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).getAbsolutePath();
path = path + "/testFile.txt";
Log.d(tag, "path : " + path);
File file=new File(path);
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write("THIS IS A TEST LINE".getBytes());
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void listDirectory(String tag, File f) {
Log.d(tag, "absolute path " + f.getAbsolutePath());
Log.d(tag, "is dir " + f.isDirectory());
Log.d(tag, "can read " + f.canRead());
Log.d(tag, "can write " + f.canWrite());
String[] fileNames = f.list();
Log.d(tag, fileNames == null ? "fileNames is null"
: "fileNames is not null");
if (fileNames != null) {
for (String string : fileNames) {
Log.d(tag, "file -- " + string);
}
}
}
I also add these lines in AndroidManifest.xml
<permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
TO:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
EDIT:
I mess up the permission.It's Now every thing works fine!

4.4 changed the file permissions for the sd card. You can't write outside of your personal directory anymore. See also: http://www.androidcentral.com/kitkat-sdcard-changes

Related

Can't delete files from internal storage folder

I want to delete all files from Download folder
I am trying this approach -
File mydir = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("Download")));
File lister = mydir.getAbsoluteFile();
System.out.println("Total files: " + lister.list().length);
for (String list : lister.list()) {
File f = new File(lister, list);
if (f.delete())
System.out.println(list + " is Deleted!");
else
System.out.println(list + " not deleted!");
}
It doesn't work, f.delete is returning false.
I have already looked at many such questions on SO, most of them suggest the use of delete() or getCanonicalFile().delete(). This is just not working.
manifest-
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
try this, this will delete all files under filePath directory
File file = new File(filePath);
if (file.isDirectory()) {
String[] children = file.list();
if (children != null) {
for (String aChildren : children) {
boolean isDelete = new File(file, aChildren).delete();
if (isDelete)
System.out.println(aChildren + " is Deleted!");
else
System.out.println(aChildren + " not deleted!");
}
}
}
Fixed it.
My app was requesting the user for READ permission only, not WRITE.
Deleting any file requires WRITE permission. So i changed READ to WRITE, it worked!
if (ContextCompat.checkSelfPermission(MainActivity.this
, Manifest.permission.**WRITE**_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
{
// ...
}
Not an answer but more robust code:
File dir = Environment.getExternalStoragePublicDirectory("Download");
if ( !dir.canWrite() )
{
Toast.makeText(context, "Can not write in directory\n\n" + dir.getAbsolutePath(), Toast.LENGTH_LONG).show();
return;
}
File files [] = dir.listFiles();
if ( files==null )
{
Toast.makeText(context, "Could not listFiles() for\n\n" + dir.getAbsolutePath(), Toast.LENGTH_LONG).show();
return;
}
for ( File file : files)
{
if ( file.isDirectory())
continue;
if ( ! file.delete())
{
Toast.makeText(context, "Could not delete\n\n" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
break;
}
}
Please try.

Saving image\file

The issue is to save image to the storage
This code worked fine, but not with Android 6 and N
What do I need to fix here?
Or as an option - using another example for saving to internal\external files
public void saveImage(Bitmap icon) {
File ff;
File file = new File(android.os.Environment.getExternalStorageDirectory(), "Folder Name");
ff = new File(file.getAbsolutePath() + file.separator + imageName + ".jpg");
if(ff.exists()){
Log.i("sharing", "File exist SD");
} else{
try {
File f = null;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
if (!file.exists()) {
file.mkdirs();
}
Log.i("sharing", "File exist Internal");
f = new File(file.getAbsolutePath() + file.separator + imageName + ".jpg");
}
FileOutputStream ostream = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, ostream);
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
And permissions from Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Thanx
You should put the uses-permission-sdk-23 tag and set the permission you want.
Then
You should check whether the permission is granted or not by calling the checkSelfPermission and pass the permission name as argument
If the permission is not granted you should gain the permissions by calling the requestPermissions method and pass the permissions names as string array and the request code
After that
A dialog will be shown to user and ask them if the permission is granted or not
Then a interface onRequestPermissionResult will be called and you should implement this into your activity class
After that
You can gain access to the requested permissions if the user granted it
I added permissions for android sdk > 22
This code works perfectly
if (ContextCompat.checkSelfPermission(HomeActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(HomeActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},23
);
}

How to create folder in external storage?

This is what I tried.
private void createFolderInExternalStorage() {
String storagePath = System.getenv("SECONDARY_STORAGE");
Log.e("storagePath->",storagePath);
String path = "not available";
if (storagePath != null) {
Log.e("Path->", "" + storagePath);
File file = new File(storagePath.toString());
Log.e("readable->", "" + file.canRead());
Log.e("writable->", "" + file.canWrite());
Log.e("executable->", "" + file.canExecute());
dir = new File(storagePath + File.separator+etFolder.getText().toString());
if (!dir.exists()) {
dir.mkdirs();
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" created",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Folder "+etFolder.getText().toString()+" already exists",Toast.LENGTH_SHORT).show();
}
path = dir.getPath();
} else {
Toast.makeText(this,"External Storage not available",Toast.LENGTH_SHORT).show();
}
tv.setText("External SDCARD path->" + path);
}
if Secondary storage is present then System.getenv("SECONDARY_STORAGE") return /storage/sdcard1 in my case but getting following:
03-21 12:02:26.827 14155-14155/com.think.teststorage E/readable->: false
03-21 12:02:26.827 14155-14155/com.think.teststorage E/writable->: false
03-21 12:02:26.828 14155-14155/com.think.teststorage E/executable->: false
Even in some devices getting the above status as true but folder creation fails.
I have added the permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Suggestions are welcome.
You can use this code to create a folder.
File dir = new File("path/of/your/folder");
try{
if(dir.mkdir()) {
System.out.println("Folder created");
} else {
System.out.println("Folder is not created");
}
}catch(Exception e){
e.printStackTrace();
}
Add this permission also :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
For further reference : see this link
Let me know if this works for you! :)
Use the following lines:
//Define the path you want
String path = Environment.getExternalStoragePublicDirectory(Environment.YOUR_DIRECTORY) + File.separator + "YourFolderName";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
YOUR_DIRECTORY is the directory where you want to create the folder, for example: DIRECTORY_DOCUMENTS, DIRECTORY_DOWNLOADS, DIRECTORY_PICTURES etc.
In your manifest should to add permission for write:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope it help!
It is very simple and straightforward in android
`
File mFolder = new File(Environment.getExternalStorageDirectory(), "Folder_Name");
if (!mFolder.exists()) {
mFolder.mkdirs();
mFolder.setExecutable(true);
mFolder.setReadable(true);
mFolder.setWritable(true);
}
`
Also include required permissions in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Just put these lines of code,
// create a File object for the parent directory
File wallpaperDirectory = new File("/sdcard/Wallpaper/");
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(wallpaperDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
and add require permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Does not work on KitKat, external, physical sdcard ??
then use use
Environment.getExternalStorageDirectory().getPath();

How to use AccessController in android?

In an Android application (API level 10),I do not use below permission in manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
So application would not write on root of external storage.But when I try to check read/write permission via AccessController by this code:
File f = Environment.getExternalStorageDirectory();
String path = f.getAbsolutePath();
String actions = "read,write";
try {
AccessController.checkPermission(new FilePermission(path, actions));
Log.d("Tag", "You have read/write permition to use : " + path);
} catch (AccessControlException e) {
Log.d("Tag", "You have not read/write permition to use : " + path);
} catch (SecurityException e) {
Log.d("Tag", "You have not read/write permition to use : " + path);
}
Result will be:
You have read/write permition to use : /storage/sdcard0
So why AccessController.checkPermission does not throw exception on root of External Storage when application has no permission to write on it?

Cannot create directory on sdcard :S

I have this code
File dir = new File(Environment.getExternalStorageDirectory() + "/" + "new_dir");
if (dir.mkdir()) {
txtView.setText(dir + " Directory created");
} else {
txtView.setText(dir + " Directory is not created");
}
and i also added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
but it always goes in the else and the directory is never made :S :S
Try This code
String newFolder = "/myFolder2";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
(!myNewFolder.mkdir())
{
Log.e(TAG, "Create dir in sdcard failed");
return;
}
User permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Categories

Resources