W/System.err: 错误: /storage/emulated/0/2854: open failed: ENOENT (No such file or directory) JAVA

时间:2021-06-20 12:08:23

标签: java android android-studio

我试图从设备的内部空间打开一个文件,但是当我尝试打开它时出现 ENOENT 错误。试图打开一个 txt。文件 拥有清单中的所有权限(读/写)

public class MainActivity extends AppCompatActivity {
private static final int READ_REQUEST_CODE=42;
private static final int PERMISSION_REQUEST_STORAGE=1000;
private String readText(String input) {
    StringBuilder str=new StringBuilder();
    try {
        File file=new File(input);
        BufferedReader br=new BufferedReader(new FileReader(file));
        String line;
        while ((line = br.readLine()) != null) {
            str.append(line);
            str.append("\n");
        }
        br.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
    return str.toString();
}
private void performFileSearch(){
    Intent intent=new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/*");
    startActivityForResult(intent,READ_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode==READ_REQUEST_CODE ){
        if(data!=null){
            Uri uri=data.getData();
            String path=uri.getPath();
            path=path.substring(path.indexOf(":")+1);
            Toast.makeText(this,""+path,Toast.LENGTH_SHORT).show();
            tv_output.setText(readText(path));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题出在 API 中,代码仅适用于 v28 及更低版本。