Android saving file to external storage

后端 未结 12 743
抹茶落季
抹茶落季 2020-11-22 03:12

I have a little issue with creating a directory and saving a file to it on my android application. I\'m using this piece of code to do this :

String filename         


        
12条回答
  •  时光说笑
    2020-11-22 03:59

    For API level 23 (Marshmallow) and later, additional to uses-permission in manifest, pop up permission should also be implemented, and user needs to grant it while using the app in run-time.

    Below, there is an example to save hello world! as content of myFile.txt file in Test directory inside picture directory.

    In the manifest:

    
    
    

    Where you want to create the file:

    int permission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    
    String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    
    if (permission != PackageManager.PERMISSION_GRANTED)
    {
         ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS_STORAGE, 1);
    }
    
    File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Test");
    
    myDir.mkdirs();
    
    try 
    {
        String FILENAME = "myFile.txt";
        File file = new File (myDir, FILENAME);
        String string = "hello world!";
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(string.getBytes());
        fos.close();
     }
     catch (IOException e) {
        e.printStackTrace();
     }
    

提交回复
热议问题