首页 > 解决方案 > 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。

你有这方面的想法吗?

感谢您的帮助。

标签: androidfilefilenotfoundexception

解决方案


谢谢blackapps,我读了文件。

我无法读取文件的原因是指向错误的方向。

改变这个:

String yourFilePath = MainActivity.this.getFilesDir() + "/" + Environment.DIRECTORY_DOWNLOADS + "/busStop.json";

对此:

File yourFilePath = MainActivity.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    

推荐阅读