我试图从设备的内部空间打开一个文件,但是当我尝试打开它时出现 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));
}
}
}
答案 0 :(得分:0)
问题出在 API 中,代码仅适用于 v28 及更低版本。