How to create/write file in the root of the Android device?
Context.openFileOutput is meant to be used for creating files private to your application. they go in your app's private data directory. you supply a name, not a path: "name The name of the file to open; can not contain path separators".
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
as for your question, you can't write to / unless you're root:
my-linux-box$ adb shell ls -l -d /
drwxr-xr-x root root 2010-01-16 07:42
$
i don't know what your API is that expects you to write to the root directory, but i'm guessing it's not an Android API and you're reading the wrong documentation ;-)
Android: how to write a file to internal storage
Use the below code to write a file to internal storage:
public void writeFileOnInternalStorage(Context mcoContext, String sFileName, String sBody){
File dir = new File(mcoContext.getFilesDir(), "mydir");
if(!dir.exists()){
dir.mkdir();
}
try {
File gpxfile = new File(dir, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
Starting in API 19, you must ask for permission to write to storage.
You can add read and write permissions by adding the following code to AndroidManifest.xml
:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
You can prompt the user for read/write permissions using:
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
and then you can handle the result of the permission request in onRequestPermissionsResult()
inside activity called from it.
Unable to write file to android root
System
is mounted ro
, if you want to try to write something inside system/etc
you should first remount it rw
.
Edit:
from the mount documentation
All files accessible in a Unix system are arranged in one big tree,
the file hierarchy, rooted at /. These files can be spread out over
several devices. The mount command serves to attach the filesystem
found on some device to the big file tree.
That`s the output on my device:
shell@android:/ $ mount
rootfs / rootfs ro,relatime 0 0
as you can see /
is mounted as read-only
Android SDK 30, write to the root of external storage
You can target SDK 30 and add MANAGE_EXTERNAL_STORAGE permission to the manifest:
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
Do note it's a dangerous permission so you'll need to request it differently, like this:
if (!Environment.isExternalStorageManager()) {
requestManageAllPermission();
return;
}
private void requestManageAllPermission() {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, REQ_MANAGE_EXTERNAL);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, REQ_MANAGE_EXTERNAL);
}
}
And you need to handle the results in:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_MANAGE_EXTERNAL) {
if (!Environment.isExternalStorageManager())
finish();
}
}
REQ_MANAGE_EXTERNAL is a int constant, can be any number you want, in my case its 2296
How can I write a file to a folder of the internal storage on Android?
As you have figured out writing to root directories in Android is impossible unless you root the device. Thats why even some apps in Play-store asking for root permissions before installing the app. Rooting will void your warranty so i don't recommend it if you don't have serious requirement.
Other than root directories you can access any folder which are visible in your Android file manager.
Below is how you can write into sd with some data - Taken from : https://stackoverflow.com/a/8152217/830719
Use these code you can write a text file in SDCard along with you need to set permission in android manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}
}
.
Related Topics
Load Image from Url in Notification Android
Manually Adding Aar with Dependency Pom/Iml File
Why There's a Separate Mutablelivedata Subclass of Livedata
How to Add Border Around Linear Layout Except at the Bottom
How to Change App Name Per Gradle Build Type
No Resource Identifier Found for Attribute '...' in Package 'Com.App....'
Recompile with -Xlint in Android Studio
What Should Be the Color of the Ripple, Colorprimary or Coloraccent? (Material Design)
Android Drag/Animation of Views
Google Play Services Out of Date. Requires 11011000 But Found 10289574
Handlers and Memory Leaks in Android
Getting Height of Text View Before Rendering to Layout
Java.Lang.Illegalstateexception: the Specified Child Already Has a Parent