问题:Android9 无法向u盘写入文件
报错:
2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W java.io.FileNotFoundException: /storage/C5AF-1F0E/MyImages1/Image-2676.png (Permission denied) 2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W at java.io.FileOutputStream.open0(Native Method) 2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W at java.io.FileOutputStream.open(FileOutputStream.java:308) 2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W at java.io.FileOutputStream.<init>(FileOutputStream.java:238) 2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W at java.io.FileOutputStream.<init>(FileOutputStream.java:180) 2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W at com.example.permissiontest.MainActivity.SaveImageUSB(MainActivity.java:203) 2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W at com.example.permissiontest.MainActivity.onClick(MainActivity.java:122) 2023-12-04 11:02:45.137 15640-15640 System.err com.example.permissiontest W at android.view.View.performClick(View.java:6597) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1194) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at android.view.View.performClickInternal(View.java:6574) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at android.view.View.access$3100(View.java:778) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at android.view.View$PerformClick.run(View.java:25885) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at android.os.Handler.handleCallback(Handler.java:873) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at android.os.Handler.dispatchMessage(Handler.java:99) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at android.os.Looper.loop(Looper.java:193) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at android.app.ActivityThread.main(ActivityThread.java:6718) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at java.lang.reflect.Method.invoke(Native Method) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 2023-12-04 11:02:45.138 15640-15640 System.err com.example.permissiontest W at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
解决方法:更改路径
本来u盘的路径为/storage/C5AF-1F0E
替换为 /mnt/media_rw/C5AF-1F0E 即可
if (Build.VERSION.SDK_INT>Build.VERSION_CODES.O){ root = root.replace("/storage","/mnt/media_rw/"); }
原因:Android 9.0中sdcard 的权限和挂载问题_sdcard_rw-CSDN博客