将文件写入android设备内部存储中的文件夹

问题描述:

我在android设备内部存储根目录中有一个名为MyFolder的文件夹。没有安装外部SD卡。可以使用以下命令检查文件夹:ES文件管理器
我想将文件写入该目录。
我尝试以下操作,但似乎都不是我想要的。那么,sd应该如何?
请帮助。

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


如果您的目录位于您的内部数据目录中应用程序,则可以编写代码。

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

来自官方文档:
https://developer.android.com/guide/topics/data/data-data.storage.html #filesExternal

设备具有可移动(SD卡)或不可移动存储(内部共享存储)。两者都称为外部存储。假设您可以在内部共享存储中创建目录,则可以编写以下代码。

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");

注意:如果必须使用getExternalStorage,则应授予存储权限。

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

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