简体   繁体   English

无法在存储根目录中创建文件?

[英]Impossible to create a file in the storage root directory?

I have a simple app am trying to finish: //listing all of the SD Cards file names in a txt file. 我有一个简单的应用程序正在尝试完成://在txt文件中列出所有SD卡文件名。

And I've tried so many ways of at least creating the file in the root storage directory but with no luck ( not in the apps private files using "getFilesDir()" ) and one of those ways are shown in the code sample. 而且,我尝试了很多方法,至少在根存储目录中创建文件,但是没有运气(不是在使用“ getFilesDir()”的应用程序私有文件中),并且这些方法之一已在代码示例中显示。 And yes i used the proper permissions. 是的,我使用了适当的权限。

Any help would be so much appreciated. 任何帮助将不胜感激。

String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    File file = new File(path, "Something.txt");
    file.mkdirs();

    String[] array = file.list();

    try {

        FileOutputStream fos = new FileOutputStream(file, true);
        OutputStreamWriter osw = new OutputStreamWriter(fos);
        osw.write(String.valueOf(array));
        osw.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

If you are writting to external storage add this permisions to your manifest file: 如果要写入外部存储,请将以下权限添加到清单文件中:

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

acording to this [Article.][1] 根据本[条款] [1]

You need to call osw.close(); 您需要调用osw.close(); for the file to be created. 用于创建文件。

After digging and playing around a bit, 经过一番挖掘和玩耍之后,

it turns out that i forgot to to call "fos.close()" and not just "osw.close()" 事实证明,我忘了打电话给“ fos.close()”而不仅仅是“ osw.close()”

as well calling "file.createNewFile()" was mandatory , "mkdirs()" isn't working for some reason. 以及必须强制调用“ file.createNewFile()”,“ mkdirs()”由于某种原因无法正常工作。

but thanks to everyone, all of your participation and effort were appreciated. 但是感谢大家,感谢您的参与和努力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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