简体   繁体   中英

FileInputStream can't read file in Android R

File file = new File(filePath);
InputStreamReader is = new InputStreamReader(new FileInputStream(file), charsetName);

simple piece of code. i checked the following:

file!=null
file.isFile()
file.exists()
file.canRead()

everything is true. The program have the permission and can actually read this existing file, but put it in a FileInputStream, it throws the following exception:

     java.io.FileNotFoundException: /storage/emulated/0/XNR/Setting.gson: open failed: EFAULT (Bad address)
        at libcore.io.IoBridge.open(IoBridge.java:492)
        at java.io.FileInputStream.<init>(FileInputStream.java:159)
        ...
     Caused by: android.system.ErrnoException: open failed: EFAULT (Bad address)
        at libcore.io.Linux.open(Native Method)
        at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
        at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
        at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
        at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7372)
        at libcore.io.IoBridge.open(IoBridge.java:478)
        at java.io.FileInputStream.<init>(FileInputStream.java:159) 
        ... 

it works well only on a api 23 emulator now. maybe the issue is cause by some new mechanics of newer version android api?

funny thing is, i developed and tested it on a android r emulator exclusively 2 months ago and everything is fine, after tested on several actuall devices, the project was deemed done and finished, it sat in my hard drive untouched for 2 months, i can even see the same.gson file generated by it. almost looks like it just went bad on it's own.

Using getFilesDir() or getExternalFilesDir(String) to access storage instead of using Environment.getExternalStorageDirectory() solved the problem, android no longer supports that since q based on the comment above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM