write a file to a folder in the android device internal storage

DriveCarefully picture DriveCarefully · Jan 17, 2018 · Viewed 7.9k times · Source

I have a folder, called MyFolder, in the android device internal storage root directory. There is no external sd card mounted. The folder can be checked using says, ES file manager I want to write a file to that directory. I try the followings but seem all are not what I want. So how should sd be? Please help.

    File sd = Environment.getExternalStorageDirectory();
    //      File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)  ;
    //      File sd = new File( Environment.getExternalStorageDirectory().getAbsolutePath());
    //      File sd = Environment.getRootDirectory()  ; // system
    //      File sd = Environment.getDataDirectory()  ; 


    backupDBPath = "MyFolder/_subfolder/mydata.txt";

    File backupDB = new File(sd, backupDBPath);

Answer

VigneshK picture VigneshK · Jan 18, 2018

If your directory located in the internal data directory of your app, you could write the code.

File directory = new File(this.getFilesDir()+File.separator+"MyFolder");

        if(!directory.exists())
            directory.mkdir();

        File newFile = new File(directory, "myText.txt");

        if(!newFile.exists()){
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try  {
            FileOutputStream fOut = new FileOutputStream(newFile);
            OutputStreamWriter outputWriter=new OutputStreamWriter(fOut);
            outputWriter.write("Test Document");
            outputWriter.close();

            //display file saved message
            Toast.makeText(getBaseContext(), "File saved successfully!",
                    Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            e.printStackTrace();
        }

From the official document: https://developer.android.com/guide/topics/data/data-storage.html#filesExternal

The device has removable(SD Card) or non-removable storage(Internal shared storage). Both are called external storage. Suppose you could create the directory in "Internal Shared storage", you could write the code below.

File directory = new File(Enviroment.getExternalStorage+File.separator+"MyFolder");//new File(this.getFilesDir()+File.separator+"MyFolder");

Note: If you have to use getExternalStorage, you should give the storage permission.

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