How can I write a file to a folder of the internal storage on Android?
Asked Answered
J

3

7

I have written a method which creates a file and writes data to the file and stores in the internal storage. When I get the absolute path or path of the file [I have added log messages to experiment with the operations on the File], it shows me that the file is getting created under the root directory and its under the /data/data/mypackagename/files/filename.txt. Nevertheless, I could find these folders on the DDMS where I could find the file which has been created by the method which I have written. But I am unable to open that file too as I don't have permissions.

When I look at my Android device, I can't find these directories. I looked up on stack overflow and some have answered that the /data/data folders in the internal storage are hidden and to access them I have to root the device which I don't want to do.

Next approach: There is a folder called as MyFiles on the android device [I am using Galaxy Tab 4 running Android 4.4 for testing]. Under this folder there is Device Storage directory which has various folders like Documents, Pictures, Music, Ringtones, Android, etc, etc.. So, the apps like camera, spread sheet apps, are able to write or save pictures into the pictures folder or txt files in the documents folder. Similarly, how could I write the file which I am creating in the function to the Documents folder or any other folder which could be accessible over the device. Please help me how could I do it, any help is appreciated.

The following is the code which I have written:

public void addLog(String power_level){
// creates a logFile in the root directory of the internal storage of the application.
// If the file does not exists, then it is created.
Log.d("AppendPower", "In addLog method");
//File logFile = new File(((Context)this).getFilesDir(), "logFile.txt");
File logFile = new File(getFilesDir(), "logFile.txt");
Log.d("FilesDir Path", getFilesDir().getAbsolutePath());
Log.d("FilesDir Name", getFilesDir().getName());
Log.d("Path on Android", logFile.getPath());
Log.d("Absolute Path on Android", logFile.getAbsolutePath());
Log.d("Parent", logFile.getParent());
if(!logFile.exists()){
    try{
        logFile.createNewFile();
    }catch(IOException io){
        io.printStackTrace();
    }
}
try{
    BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
    writer.write("Battery level reading");
    writer.append(power_level);
    Log.d("Power_Level in try", power_level);
    writer.newLine();
    writer.close();
}catch(IOException e){
    e.printStackTrace();
}

}

Jeremie answered 7/5, 2015 at 4:48 Comment(0)
A
9

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://mcmap.net/q/334960/-how-to-create-text-file-and-insert-data-to-that-file-on-android

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();
    }
   }  

.

Alcantara answered 20/5, 2015 at 2:11 Comment(0)
B
1

1) If your purpose is debugging, you may just write to the /sdcard/. It always works.

2) Again, if your purpose is debugging, you may try to set read permissions on your app's directories. A while ago it worked for me on some Android devices (but did not work on at least one device).

Biographer answered 7/5, 2015 at 6:8 Comment(3)
All the devices won't have sdcard right. Now-a-days everyone has the internal storage on their device. And Its not exactly for the debugging. I want to write the file to the internal storage!Jeremie
/sdcard/ will work. It usually means the "built-in" sd card, which is not really a sd card, but for compatibility it exists. If your java code writes to /sdcard/ and adb pull reads from the same /sdcard/, there's no problem whether or not it is a real sd.Biographer
+1 . Yes I got it. Thanks a lot. I didn't knew that the internal storage is nothing but the built in sd card.Jeremie
P
0

Add this permission in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Then use this shortest recipe:

try
{
   FileOutputStream fos = 
      openFileOutput("myfile.txt", getApplicationContext().MODE_PRIVATE);
   fos.write("my text".getBytes());
   fos.close();
}
catch (Exception exception)
{
   // Do something, not just logging
}

It will be saved in "/data/data/my.package.name/files/" path.

Politic answered 7/1, 2019 at 0:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.