java.io.FileNotFoundException: /storage/emulated/0/Notes/fact50Result.txt: open failed ENOENT (No such file or directory)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47349953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:35:20  来源:igfitidea点击:

java.io.FileNotFoundException: /storage/emulated/0/Notes/fact50Result.txt: open failed ENOENT (No such file or directory)

javaandroid

提问by Nick

I am trying to export the results of a factorial calculation in a txt file. I found this code that looked quite straight forward from this article here.However I'm getting the error on the title. What am I doing wrong?

我正在尝试将阶乘计算的结果导出到 txt 文件中。我发现这段代码从这篇文章中看起来很直接但是我收到了标题错误。我究竟做错了什么?

I have typed this into the manifest:

我已将其输入到清单中:

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

And this is my code related to saving:

这是我与保存相关的代码:

    public void save(View v) {
     if(numOnRAM!=-1) {
         EditText text = (EditText) findViewById(R.id.resultTextBox);
         String data = text.getText().toString();
         generateNoteOnSD(this,"fact"+numOnRAM+"Results.txt", data);
     }
}

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "File "+sFileName+" saving success!", Toast.LENGTH_LONG).show();

    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();//After adding this 
//toast message did I realise the error thar occurs.

    }
}

回答by Michael Dodd

As discussed in the comments, you need to request permissions at runtimeto allow your app to write to external storage. You can check if your app has the permission already by using checkSelfPermission(). For example:

正如评论中所讨论的,您需要在运行时请求权限以允许您的应用程序写入外部存储。您可以使用checkSelfPermission(). 例如:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
    // Do the file write
} else {
    // Request permission from the user
    ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
    ...
}

In order to handle this permission request, you'll also need to implement onRequestPermissionsResult()from OnRequestPermissionsResultCallback, for example:

为了处理这个权限请求,你还需要实现onRequestPermissionsResult()from OnRequestPermissionsResultCallback,例如:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 0:
            // Re-attempt file write
    }
}

Read the documentation for full information.

阅读文档以获取完整信息。

回答by Eby Cloudins

I think you have to request permission on runtime. Please check the code below:

我认为您必须在运行时请求许可。请检查以下代码:

 final private int REQUEST_CODE_ASK_PERMISSIONS = 123;

      private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
            ActivityCompat
                    .requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ASK_PERMISSIONS);
        }
    }

        @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

回答by Андрей Алексеев

For anyone having the same issue, you can remove the android:MaxSdkVersion attribute from the merged manifest as follows.

对于遇到相同问题的任何人,您可以从合并的清单中删除 android:MaxSdkVersion 属性,如下所示。

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