setReadOnly not working - android

I am using setReadOnly method to make my app's directory stored on my SD card 'Read-only'. However this method when called is returning 'false' even though I have provided the app with android.permission.WRITE_EXTERNAL_STORAGE permission in the manifest.
Here's my code :
is.close();
fos.close();
Decompress d = new Decompress(productDirectory + "/downloadedfile.zip", productDirectory + "/unzipped/");
d.unzip();
File zipfile = new File(productDirectory + "/downloadedfile.zip");
zipfile.delete();
productDirectory = new File(Environment.getExternalStorageDirectory().toString() + "/zipfiledemo");
boolean isWriteLocked = productDirectory.setReadOnly();
Log.v("Writing access locked",">>>>>>>>>>>>>>>>>>>" + isWriteLocked);

You should define permission android.permission.MOUNT_UNMOUNT_FILESYSTEMS in AndroidManifest.xml, it means you can create file and delete file on the SDCard.

Related

Android File.mkdirs() returns false while trying to create a directory in sdcard

I know this is a many times asked question in Stackoverflow and I have seen those questions. The answers suggested checking the permission, restarting device, check if the parent directory exists etc. I tried all of them and its still not working.
I have Manifest.permission.WRITE_EXTERNAL_STORAGE permission specified in manifest.
The following is my code.
File newFile = new File(parent.getCanonicalPath() + "/" + dirName + "/");
if(!newFile.exists()){
boolean created = newFile.mkdirs();
if(!created){
int permission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
boolean permissionGranted = (permission == PackageManager.PERMISSION_GRANTED);
Log.e(getClass().getSimpleName(), "Could not create directory "
+ ", Parent exists : " + parent.exists()
+ ", Parent Dir writable : " + parent.canWrite()
+ ", Permission granted : " + permissionGranted);
}
}
And the log prints
Could not create directory, Parent exists : true, Parent Dir writable : true, Permission granted : true
I have gained write permission to sdcard through its TreeUri and then I converted the tree uri to actual path to use it with the File class.
My minSdkVersion is 19 and targerSdkVersion is 25
What am I doing wrong?
Edit :
I tried all of the above suggestions but failed. Now, I fixed the issue by using DocumentFile. I can now create new directories and files. But still I am not sure about what's happening with File. Can anyone tell me what is happening?
I did the test on,
Device : Lenovo A2010-A
Android version : 5.1
Replace
boolean created = newFile.mkdirs();
with
boolean created = newFile.mkdir();
You should not use getCanonicalPath and use getAbsolutePath instead. Below is how I create a new folder:
File newFile = new File(parent,dirName);
if(!newFile.exists()){
boolean created = newFile.mkdirs();
}
Replace parent.getCanonicalPath() to Environment.getExternalStorageDirectory()
File myDirectory = new File(Environment.getExternalStorageDirectory(), dirName);
if(!myDirectory.exists()) {
//create file if not generated
myDirectory.mkdirs();
}else {
//not created file
}

Android Studios Serialization. Attempt to get length of null array

Okay, so in my project I am trying to serialize a chess game by writing to a folder named data. I did this in eclipse, and it was able to work. However, when I brought it into android studios I got the error of trying to get the length of a null array. Here is my method:
public static void writeData() throws IOException {
System.out.println("WRiting data");
File folder = new File("data" + File.separator);
folder.mkdir();
String[] directories = folder.list();
for (String name : directories) { //error here
File ff = new File(folder + File.separator + name);
if (ff.isDirectory()) {
deleteDirectory(ff);
}
}
//add all user data
for (game u : info.games) {
File f = new File("data" + File.separator + u.name); //make a file with user name
f.mkdir(); //make the file a directory
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(f + File.separator + "game-state"));
//create stream with file name at the end
oos.writeObject(u);
//write objects
oos.close();
}
}
Also, I looked at previous questions and changed my manifest file to allow for the permissions of writing and reading data.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The app does not crash when I read data. However, it crashes when I try to write data. Going crazy over here. Thank you for your help.
This may be due to marshmellow permission request ,you have to call permission request at runtime .
go through link
https://developer.android.com/training/permissions/requesting.html

how to create a folder in android External Storage Directory?

I cannot create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String Path = Environment.getExternalStorageDirectory().getPath().toString()+ "/Shidhin/ShidhiImages";
System.out.println("Path : " +Path );
File FPath = new File(Path);
if (!FPath.exists()) {
if (!FPath.mkdir()) {
System.out.println("***Problem creating Image folder " +Path );
}
}
Do it like this :
String folder_main = "NewFolder";
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
If you wanna create another folder into that :
File f1 = new File(Environment.getExternalStorageDirectory() + "/" + folder_main, "product1");
if (!f1.exists()) {
f1.mkdirs();
}
The difference between mkdir and mkdirs is that mkdir does not create nonexistent parent directory, while mkdirs does, so if Shidhin does not exist, mkdir will fail. Also, mkdir and mkdirs returns true only if the directory was created. If the directory already exists they return false
getexternalstoragedirectory() is already deprecated. I got the solution it might be helpful for you. (it's a June 2021 solution)
Corresponding To incliding Api 30, Android 11 :
Now, use this commonDocumentDirPath for saving files.
Step: 1
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step: 2
public static File commonDocumentDirPath(String FolderName){
File dir = null ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File (Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+ "/"+FolderName );
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/"+FolderName);
}
return dir ;
}
The use of Environment.getExternalStorageDirectory() now is deprecated since API level 29, the option is using:
Context.getExternalFilesDir().
Example:
void createExternalStoragePrivateFile() {
// Create a path where we will place our private file on external
// storage.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
try {
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
InputStream is = getResources().openRawResource(R.drawable.balloons);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
}
}
void deleteExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
file.delete();
}
boolean hasExternalStoragePrivateFile() {
// Get path for the file on external storage. If external
// storage is not currently mounted this will fail.
File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
return file.exists();
}
I can create a folder in android External Storage Directory.
I have added permissing on manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is my code:
String folder_main = "Images";
File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");
if (!outerFolder.exists()) {
outerFolder.mkdirs();
}
if (!outerFolder.exists()) {
inerDire.createNewFile();
}
outerFolder.mkdirs(); // This will create a Folder
inerDire.createNewFile(); // This will create File (For E.g .jpg
file)
we can Create Folder or Directory on External storage as :
String myfolder=Environment.getExternalStorageDirectory()+"/"+fname;
File f=new File(myfolder);
if(!f.exists())
if(!f.mkdir()){
Toast.makeText(this, myfolder+" can't be created.", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this, myfolder+" can be created.", Toast.LENGTH_SHORT).show();
}
and if we want to create Directory or folder on Internal Memory then we will do :
File folder = getFilesDir();
File f= new File(folder, "doc_download");
f.mkdir();
But make Sure you have given Write External Storage Permission.
And Remember that if you have no external drive then it choose by default to internal parent directory.
I'm Sure it will work .....enjoy code
If you are trying to create a folder inside your app directory in your storage.
Step 1 : Add Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step 2 : Add the following
private String createFolder(Context context, String folderName) {
//getting app directory
final File externalFileDir = context.getExternalFilesDir(null);
//creating new folder instance
File createdDir = new File(externalFileDir.getAbsoluteFile(),folderName);
if(!createdDir.exists()){
//making new directory if it doesn't exist already
createdDir.mkdir();
}
return finalDir.getAbsolutePath() + "/" + System.currentTimeMillis() + ".txt";
}
This is raw but should be enough to get you going
// create folder external located in Data/comexampl your app file
File folder = getExternalFilesDir("yourfolder");
//create folder Internal
File file = new File(Environment.getExternalStorageDirectory().getPath( ) + "/RICKYH");
if (!file.exists()) {
file.mkdirs();
Toast.makeText(MainActivity.this, "Make Dir", Toast.LENGTH_SHORT).show();
}
Try adding
FPath.mkdirs();
(See http://developer.android.com/reference/java/io/File.html)
and then just save the file as needed to that path, Android OS will create all the directories needed.
You don't need to do the exists checks, just set that flag and save.
(Also see : How to create directory automatically on SD card
I found some another thing too :
I had the same problem recently, and i tryed abow solutions and they did not work...
i did this to solve my problem :
I added this permission to my project manifests file :
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
(plus READ and WRITE permissions) and my app just worked correctly.
try {
String filename = "SampleFile.txt";
String filepath = "MyFileStorage";
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from External Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}

Android: Create a file from a Service

I have been successfully able to create files in my apps local directory using the below code
File appDir = new File(this.getExternalFilesDir(null), "my_folder");
if (!appDir.exists())
{
boolean result = appDir.mkdir();
if (!result) {
Log.i(Util.TAG, LOG_LABEL
+ ":: Unable to create \"my_folder\" Directory : "
+ appDir.getAbsolutePath()
+ " Directory already exists !");
}
}
File HTMLFile = new File(appDir,"html.txt");
But now when I tried to do the same from a service, the file was not being created, I even checked using 'HTMLFile.exists()' and it says the file does not exist.
My question is, Is it actually possible to create files from a service? or am I missing something here.
It is possible to write to the storage of your android: by the help of the following methods
Make sure you provide uses permission to write and read from storage in manifest file.
I have used this code:
private File newFile;
public ListenNotification() {
Log.d("Service","InConstrutor");
newFile=newFile(Environment.getExternalStorageDirectory(),"NotificationFromService");
if(!newFile.exists()){
Log.d("Service","Created");
newFile.mkdir();
}
else{
Log.d("Service","Existed");
}
}
File HTMLFile = new File(newFile,"html.txt");

Check if file exists on SD card on Android

I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
How can I check whether this file exists?
This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
See this file System in android : Working with SDCard’s filesystem in Android
you just check
if(file.exists()){
//
}
*Using this you can check the file is present or not in sdcard *
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
You have to create a file, and set it to be the required file, and check if it exists.
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
Have Fun!
The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.
Also, make sure you have permission to access the SD card.
check IF condition with Boolean type like
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}

Categories

Resources