我在网上搜索了很多解决方案。但是,似乎到处使用的代码在这里仍然无法正确执行。这可能是一个愚蠢的错误,但它使我在数小时内处于优势。
public class FileActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
Intent intent = getIntent();
String filepath = intent.getStringExtra("KEY");
TextView pane = findViewById(R.id.TextPanel);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(filepath));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),filepath,Toast.LENGTH_LONG).show();
e.printStackTrace();
}
pane.setText(text);
}
}
问题:我收到IOException。虽然文件路径是绝对的。
编辑: Works。它需要在代码中指定权限。
使用以下代码来自:Exception 'open failed: EACCES (Permission denied)' on Android
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
答案 0 :(得分:0)
如果确定文件路径正确,则需要验证是否具有文件读写权限。请在AndroidManifest.xml上将其写入。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
如果Android设备的版本号大于或等于6,则需要获取运行时权限。