1

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

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

2 回答 2

6

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

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-storage.html#filesExternal

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

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

注意:如果你必须使用getExternalStorage,你应该给予存储权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2018-01-18T07:58:27.077 回答
-1

从应用程序中,您无法在设备内部存储的任何位置写入文件,它必须位于应用程序的内部目录或应用程序缓存目录中。

将文件保存到内部存储时,您可以通过调用以下两种方法之一获取适当的目录作为文件:

getFilesDir() 返回代表应用程序内部目录的文件。

getCacheDir() 返回代表应用程序临时缓存文件的内部目录的文件。

你可以写:

String backupDBPath = "/_subfolder/";
String fileName = "mydata.txt";
File file = new File(context.getFilesDir() + backupDBPath, filename);

更多信息在这里:

https://developer.android.com/training/data-storage/files.html

于 2018-01-17T15:21:34.203 回答