Android Studio写入外部存储报错:路径引发IOException问题咨询
Android创建文件抛出IOException的原因及解决
路径错误是核心问题:你写的路径
":/storage/sdcard0/"开头多了个冒号,正确的根路径应该是/storage/sdcard0/。但更不推荐硬编码路径——不同品牌设备的外部存储路径可能有差异,建议用系统API获取:Environment.getExternalStorageDirectory().getPath(),能适配绝大多数设备。权限问题不能忽略:
- 除了在Manifest中声明
WRITE_EXTERNAL_STORAGE权限,Android 6.0(API 23)及以上系统必须动态申请权限,仅Manifest声明不会生效,用户未授权时会导致文件写入失败。 - Android 10(API 29)及以上启用了Scoped Storage,直接操作外部存储根目录会受限制,建议优先使用应用专属目录(
getExternalFilesDir(null)),这个目录无需额外权限,且卸载应用时会自动清理;如果要存公共目录,需要用MediaStore API。
- 除了在Manifest中声明
修正后的代码示例:
// 先处理动态权限申请 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001); } else { createCsvFile(); } // 创建文件的方法 private void createCsvFile() { // 用系统API获取外部存储路径 String storagePath = Environment.getExternalStorageDirectory().getPath(); File csvFile = new File(storagePath, "ratings.csv"); try { // 确保父目录存在,避免目录不存在导致创建失败 if (!csvFile.getParentFile().exists()) { csvFile.getParentFile().mkdirs(); } if (!csvFile.exists()) { boolean isCreated = csvFile.createNewFile(); // 可根据isCreated判断是否创建成功 } } catch (IOException e) { e.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者OttoIEM
相关产品推荐
相关产品推荐

