如何将文件保存到 Android 中的任何特定路径

How to save a File to any specific path in Android

我可以创建文件。它在 /data/data/com.mypackage.app/files/myfile.txt 上创建。但我想在 Internal Storage/Android/data/com.mypackage.app/files/myfiles.txt 位置创建。我怎样才能做到这一点?

代码:

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

}

更新:

我解决了这个问题。也许有人可以提供帮助。只改变这一行。

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

您可以使用以下方法获取根目录:

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

您也可以使用 nullDIRECTORY_MUSICDIRECTORY_PODCASTSDIRECTORY_RINGTONESDIRECTORY_ALARMS、[=17,而不是 DIRECTORY_PICTURES =]、DIRECTORY_PICTURESDIRECTORY_MOVIES.

在此处查看更多内容: