51

I am developing a simple android application and I need to write a text file in internal storage device. I know there are a lot of questions (and answers) about this matter but I really cannot understand what I am doing in the wrong way.

This is the piece of code I use in my activity in order to write the file:

public void writeAFile(){
    String fileName = "myFile.txt";
    String textToWrite = "This is some text!";
    FileOutputStream outputStream;

   try {
      outputStream = openFileOutput(fileName , Context.MODE_PRIVATE);
      outputStream.write(textToWrite.getBytes());
      outputStream.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
}

I really cannot understand which mistake I am doing. In addition, I have tried this project on my emulator in Android Studio and my phone in order to understand where I am doing something wrong but even with that project no file is written neither on the phone or on the emulator.

EDIT: I know that no file is written to my internal storage because I try to read the content of the file, after I have written to it, with this code:

public void ReadBtn(View v) {
    //reading text from file
    try {
        FileInputStream fileIn=openFileInput("myFile.txt");
        InputStreamReader InputRead= new InputStreamReader(fileIn);

        char[] inputBuffer= new char[READ_BLOCK_SIZE];
        String s="";
        int charRead;

        while ((charRead=InputRead.read(inputBuffer))>0) {
            String readstring=String.copyValueOf(inputBuffer,0,charRead);
            s +=readstring;
        }
        InputRead.close();
        textmsg.setText(s);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Nothing is shown at all.

delca85
  • 1,176
  • 2
  • 10
  • 17

8 Answers8

65

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.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
Sandeep dhiman
  • 1,863
  • 2
  • 17
  • 22
  • 10
    Do not just catch an exception without logging it. – CommonsWare Jun 16 '17 at 12:08
  • 1
    @CommonsWare better doing than just complaining! ;) – Heitor Dec 30 '17 at 07:16
  • 68
    why do you use EXTERNAL storage permissions when reading/writing from INTERNAL? – Dan Mar 06 '18 at 00:06
  • @Maverick EXTERNAL means access to storage including directories of other application (directory `/sdcard`). – jiwopene Aug 19 '18 at 12:58
  • 2
    So you mean to say that EXTERNAL is the only way to write to disk. The name is misleading. – Dan Aug 19 '18 at 20:37
  • Sorry if my question seems silly, but why do you create a `File gpxFile` when you already have `File file` ? – Jacks Aug 22 '18 at 13:01
  • 5
    what is 'context'? – john k Oct 08 '18 at 19:34
  • 5
    According to the official Android reference [page](https://developer.android.com/reference/android/Manifest.permission#WRITE_EXTERNAL_STORAGE): _Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by `Context.getExternalFilesDir(String)` and `Context.getExternalCacheDir()`._ – Neph Mar 13 '20 at 12:19
20

no file is written neither on the phone or on the emulator.

Yes, there is. It is written to what the Android SDK refers to as internal storage. This is not what you as a user consider to be "internal storage", and you as a user cannot see what is in internal storage on a device (unless it is rooted).

If you want to write a file to where users can see it, use external storage.

This sort of basic Android development topic is covered in any decent book on Android app development.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I suppose the internal storage where this application would write is the root one (I expect to find a file in /data/data/[package-name]). I am reading from the link you provide me that it is not always true. Anyway, I am trying to read this file from the app but nothing is shown. I am going to edit my question to clarify this point. – delca85 Jun 16 '17 at 11:03
  • 1
    @delca85: Well, your stream I/O code is kinda nasty and not parallel in implementation. Use an `OutputStreamWriter` wrapped around your `OutputStream` to `write()` the `String` in a single call, without conversion to bytes. Then, [use an `InputStreamReader`](http://stackoverflow.com/a/309718/115145) to read in the text in larger blocks (e.g., 8192 bytes). – CommonsWare Jun 16 '17 at 11:42
  • @CommonsWare: thank you for your advice. I suppose my problem was related to the use of openFileOutput, using the code posted by Sandeep Dipham, I am able to write this file. According to you, is that the only solution? Now I am trying to read with FileInputStream but I keep on having some problems. – delca85 Jun 16 '17 at 11:49
  • 1
    @delca85: I also tend to use `getFilesDir()`, just because it is more flexible. There is nothing wrong with using `openFileInput()`/`openFileOutput()` though. – CommonsWare Jun 16 '17 at 12:08
  • @CommonsWare Sorry if I look like pretty dumb, but why am I not able to retrieve file when I use `openFileInput() / openFileOutput()` but I can do that with `getFilesDir()`? – delca85 Jun 16 '17 at 12:19
  • @delca85: I have no idea. – CommonsWare Jun 16 '17 at 12:58
4

Save to Internal storage

data="my Info to save";

try {

    FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
    fOut.write(data.getBytes());
    fOut.close();   

    Toast.makeText(getBaseContext(), "file saved", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Read from Internal storage

try {

    FileInputStream fin = openFileInput(file);
    int c;
    String temp="";

    while( (c = fin.read()) != -1){
        temp = temp + Character.toString((char)c);
    }
    tv.setText(temp);
    Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
}
catch(Exception e){
}
Fakhriddin Abdullaev
  • 4,169
  • 2
  • 35
  • 37
4

Android 11 Update

Through Android 11 new policies on storage, You cannot create anything in the root folder of primary external storage using Environment.getExternalStorageDirectory() Which is storage/emulated/0 or internal storage in file manager. The reason is that this possibility led to external storage being just a big basket of random content. You can create your files in your own applications reserved folder storage/emulated/0/Android/data/[PACKAGE_NAME]/files folder using getFilesDir() but is not accessible by other applications such as file manager for the user! Note that this is accessible for your application!

Final solution (Not recommended)

By the way, there is a solution, Which is to turn your application to a file manager (Not recommended). To do this you should add this permission to your application and the request that permission to be permitted by the user:

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

Thoriya Prahalad has described how to this job in this stackoverflow post.

Amir Fo
  • 5,163
  • 1
  • 43
  • 51
3

To view files on a device, you can log the file location >provided by methods such as File.getAbsolutePath(), and >then browse the device files with Android Studio's Device >File Explorer.

I had a similar problem, the file was written but I never saw it. I used the Device file explorer and it was there waiting for me.

Device File Manager

    String filename = "filename.jpg";
    File dir = context.getFilesDir();
    File file = new File(dir, filename);

    try {
        Log.d(TAG, "The file path = "+file.getAbsolutePath());
        file.createNewFile();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
Sameh Yassin
  • 424
  • 3
  • 9
0

Have you requested permission to write to external storage?

https://developer.android.com/training/basics/data-storage/files.html#GetWritePermission

Perhaps your try\catch block is swallowing an exception that could be telling you what the problem is.

Also, you do not appear to be setting the path to save to.

e.g: Android how to use Environment.getExternalStorageDirectory()

Kuffs
  • 35,581
  • 10
  • 79
  • 92
  • Sorry just noticed you said internal storage not external;. The other points could still apply though. Are you sure the file is not being created? The default path is a rather convoluted one and you could simply be looking in the wrong place. – Kuffs Jun 16 '17 at 10:47
  • No path specification is needed when openFileOutput is used. I am going to use getFilesDir() to discover if I am doing something wrong with the path. – delca85 Jun 16 '17 at 11:24
0

To write a file to the internal storage you can use this code :

val filename = "myfile"
    val fileContents = "Hello world!"
    context.openFileOutput(filename, Context.MODE_PRIVATE).use {
            it.write(fileContents.toByteArray())
    }
Hesham Morsy
  • 433
  • 3
  • 13
-2

This Answer worked for me for android 11+ !! check it out, hopefully it'll work for you too

https://stackoverflow.com/a/66366102/16657358[1]

[(btw, int SDK_INT = 30; it confused me lol so thought i should mention)]

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/30224556) – Robert Oct 31 '21 at 19:19
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 31 '21 at 23:05