Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

java - How to have permissions to save file into SD Card on Android

I recently created an application in which I share files through an intent filter, so that an user can save the shared file in any folder on the system.

The purpose of this app is to share a file from WhatsApp (or any other app) and select through a file explorer the location to save it.

SaveFile app print screen

It is working correctly for internal storage. It is possible to save the file in any folder within that location. However, when selecting the external storage folder (external "SD card"), it does not allow saving, and displays a message indicating permission error, throwing the following exception:

java.io.IOException: open failed: EACCES (Permission denied)
  at java.io.File.createNewFile(File.java:939)
  at br.com.luansilveira.savefile.MainActivity.btSalvarClick(MainActivity.java:370)

In the application manifest, storage permissions have already been requested:

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

and when starting app, they are requested for the user.

Below is the code where file is written:

public void btSalvarClick(View view) {
        String filename = diretorioAtual.getAbsolutePath() + "/" + edNomeArquivo.getText().toString();
        try {
            File novoArquivo = new File(diretorioAtual, edNomeArquivo.getText().toString());
            if (!novoArquivo.createNewFile()) {
                Toast.makeText(this, "O arquivo já existe!", Toast.LENGTH_LONG).show();
                return;
            }

            FileOutputStream outputStream = new FileOutputStream(novoArquivo);
            outputStream.write(getBytes(uri));
            outputStream.close();

            finish();
            Toast.makeText(this, "Arquivo salvo", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "Sem permiss?o para salvar neste local", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Erro ao salvar: 
" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...