How to write a file in Android

First, we need to define a path. We can’t save files everywhere because of the different permissions.

We write our file to the project path.

  1. Create Empty Project 
  2. Start emulator or your device
  3. Go to View ->Tool Windows->Device File Explorer
  4. Select directory Data->Data 

6.Select your project folder and copy path(right mouse click)

My path is

/data/data/learn.hq.readwritefiles/textFile.txt
 protected void onCreate(Bundle savedInstanceState) {
        EditText text = findViewById(R.id.editText);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        File path = new File("/data/data/learn.hq.readwritefiles/textFile.txt");
        writeFileString(path,"kasldklasklksad");
}
public void writeFileString(File ft,String text){


        try{
            FileWriter ftw = new FileWriter(ft,true);
            BufferedWriter bw = new BufferedWriter(ftw);

            bw.write(text);
            bw.write("\n");
            bw.close();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }


    }
}

Well, this seems very easy but the problem begins if we want to save our files to external directories like Downloads folder or Documents etc…

We have to set the permissions first in Android manifest : 

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

Even if you have permissions you will not save the file to external storage.You have to ask the user to grant your application permissions.

on Create(….){………

checkPermission();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            ... //Do Something...
        }

ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

OnRequest Method

public boolean checkPermission(){
    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        Log.i("Permission ","You have permission");
        return true;
    }
    return false;
}
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case EXTERNAL_STORAGE_REQUEST_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    createDirectory();
                } else {
                    Toast.makeText(this,  "Read/Write External Storage Not Granted", Toast.LENGTH_LONG).show();
                }
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *