android - android FileNotFoundException 在内部存储中获取文件时
问题描述
我正在尝试将 JSON 文件打印为 android 中的字符串。
单击按钮后,将打印 JSON。
这些是该按钮的代码:
public void startReadJSONButtonHandler(View view) throws Exception {
String yourFilePath = MainActivity.this.getFilesDir() + "/" + Environment.DIRECTORY_DOWNLOADS + "/busStop.json";
System.out.println(yourFilePath);
File yourFile = new File(yourFilePath);
FileInputStream fin = new FileInputStream(yourFile);
String ret = convertStreamToString(fin);
fin.close();
System.out.println(ret);
}
该文件确实存在于“yourFilePath”中,我在文件资源管理器中检查了它。
当我运行它时,它会返回这种错误:
Caused by: java.io.FileNotFoundException: /data/user/0/com.google.android.gms.location.sample.locationupdates/files/Download/busStop.json: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:492)
at java.io.FileInputStream.<init>(FileInputStream.java:160)
at com.google.android.gms.location.sample.locationupdates.MainActivity.startReadJSONButtonHandler(MainActivity.java:418)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:7448)
at android.view.View.performClickInternal(View.java:7425)
at android.view.View.access$3600(View.java:810)
at android.view.View$PerformClick.run(View.java:28305)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
它说 JSON 文件不存在,因此返回 FileNotFoundException。
你有这方面的想法吗?
感谢您的帮助。
解决方案
谢谢blackapps,我读了文件。
我无法读取文件的原因是指向错误的方向。
改变这个:
String yourFilePath = MainActivity.this.getFilesDir() + "/" + Environment.DIRECTORY_DOWNLOADS + "/busStop.json";
对此:
File yourFilePath = MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
推荐阅读
- msbuild - 使用 Microsoft.CodeAnalysis Nuget 包的应用程序是否需要在最终用户的计算机上安装一些额外的 SDK/软件?
- for-loop - 在 golang 中编写 while (for) 的更好方法
- json - 使用 Codable 解析 JSON 数据
- sql - SQL:达到 SUM 阈值后显示记录
- excel - 包含参考单元格的公式
- android - 无法解析符号“MultiDex”
- firebase - Firestore .setData 被未创建的更新规则阻止
- excel - 在单元格保持不变的情况下计算运行总数
- html - width = 100% 在 IE、Microsoft Edge 浏览器中无法正常工作
- html - 如何防止 Windows 讲述人阅读
text</h1> <div id="body"><p>When I set focus on the body tag, Windows narrator reads the text in tag. How can I prevent this from happening?</p> <p>I've tried aria-hidden="true", role="presentation