简体   繁体   中英

How to save a File to any specific path in Android

I can create file. It's creating on /data/data/com.mypackage.app/files/myfile.txt. But i want to create on Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt location. How can i do this?

Codes:

public void createFile()  {

    File path  = new File(this.getFilesDir().getPath());
    String fileName = "myfile.txt";
    String value = "example value";

    File output = new File(path + File.separator + fileName);

    try {
        FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
        outputWriter.write(value);
        outputWriter.close();
        //display file saved message
        Toast.makeText(getBaseContext(), "File saved successfully!",
                Toast.LENGTH_SHORT).show();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

}

UPDATE :

I fixed the problem. Maybe someones to helps. Only changing this line.

File output = new File(getApplicationContext().getExternalFilesDir(null),"myfile.txt");

You can use the following method to get the root directory:

File path = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);

Instead of DIRECTORY_PICTURES you can as well use null or DIRECTORY_MUSIC , DIRECTORY_PODCASTS , DIRECTORY_RINGTONES , DIRECTORY_ALARMS , DIRECTORY_NOTIFICATIONS , DIRECTORY_PICTURES , or DIRECTORY_MOVIES .

See more here:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM