Home > Net >  How to store a file in public directories
How to store a file in public directories

Time:05-17

i know this question might have a simple response, but i can0t find anything that fits my case in the docs.

What i'm trying to achieve is to store a file (E.G test.txt) in /download directory or any other dir that is public and visible by any resource finder.

I don't find any hint of the correct approach in the docs or even if there is the possibility to do it anymore.

Thank you a lot

CodePudding user response:

Try this

val dir = File(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))

    if (!dir.exists()) {
        dir.mkdirs()
    }

And don't forget to set this permission in your manifest.xml:

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

or you can refer this link also [https://stackoverflow.com/a/28183933/15529296]

CodePudding user response:

To create a file in a custom directory inside the public storage with Java:

 String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)   "/YOUR_FOLDER_NAME_HERE";

 File dir = new File (path);
 dir.mkdirs();
        
path = path   File.separator   "YOUR_FILE_NAME";

File file = new File(path); 

After that do whatever you want with your file.

As Yash said don't forget the permission...

  • Related