0

I'm trying to create a folder on external storage with no success.Although i've managed to create a folder in my app's directory, i can't do the same for external storage and i also get false when i call canWrite().I have declared the WRITE_EXTERNAL_PERMISSION on manifest.

Here is my code for my app's directory

 File file1=new File(context.getFilesDir(), "//test1");
 file1.mkdir();
 System.out.println(file1.canWrite());

and for ExternalStorage respectively

File file2=new File(Environment.getExternalStorageDirectory(), "//test2");
file2.mkdir();
System.out.println(file2.canWrite());

In the first case the folder gets created and i get true on println.On the second one folder does not get created and i get false on println.

tasgr86
  • 299
  • 2
  • 7
  • 17
  • 1
    I'd start by getting rid of the duplicate slashes. Beyond that, [you appear to be having problems getting the `WRITE_EXTERNAL_STORAGE` permission](https://commonsware.com/blog/2015/08/31/hey-where-did-my-permission-go.html). – CommonsWare Apr 01 '16 at 13:06
  • Possible duplicate of [Can't create folder on external storage on android](http://stackoverflow.com/questions/22366217/cant-create-folder-on-external-storage-on-android) –  Apr 01 '16 at 13:09
  • @CommonsWare That was very helpful.The problem was that i was targeting version 23.I would never have found it! – tasgr86 Apr 01 '16 at 13:42

2 Answers2

0

Add Below Permission i your manifest.xml android:name="android.permission.WRITE_EXTERNAL_STORAGE"

          String PATH = Environment.getExternalStorageDirectory() + "/download/YourPath";
          String fileName="Name for your File";           

          File file = new File(PATH);
          file.mkdirs();

          File outputFile = new File(file, fileName);
          FileOutputStream fos = new FileOutputStream(outputFile);

          InputStream is = c.getInputStream();

          byte[] buffer = new byte[1024];
          int len1 = 0;
          while ((len1 = is.read(buffer)) != -1) 
          {

              fos.write(buffer, 0, len1);
          }
          fos.close();
          is.close();
Raghavendra B
  • 441
  • 3
  • 10
0

This will create a directory,if you use comma,it means "//test2" will become a file name

String string = Environment.getExternalStorageDirectory().getPath() + "/test2";
File file = new File(string, "file_name");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(your_data);
fileOutputStream.flush();
fileOutputStream.close();
0x5050
  • 1,221
  • 1
  • 17
  • 32
Karthik
  • 381
  • 2
  • 10
  • I get your point but the problem was i could't write anything when i called getExternalStorageDirectory, file or directory – tasgr86 Apr 01 '16 at 13:43
  • FileOutputStream fileOutputStream = new FileOutputStream(file2); fileOutputStream.write(your data); fileOutputStream.flush(); fileOutputStream.close(); – Karthik Apr 01 '16 at 13:46