从 Android 上的文件加载 .json 文件时出现问题

Issues loading .json file from file on Android

首先感谢大家能帮到我

在我的项目中,我必须在我的应用程序中上传一个文件 .json,然后我从浏览器中获取它。

我使用 Intent Filter 从 Manifest.xml 处理它,如下所示:

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="file"  android:host="*" android:pathPattern=".*\.json" android:mimeType="*/*"  />
    </intent-filter>

然后,根据 MainActivity.java,我构建了文件对象并从创建的文件中获取字符串结果:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = getIntent();
        String action = intent.getAction();
        Uri uri = intent.getData();

        if (action != null){
            if (action.compareTo(Intent.ACTION_VIEW) == 0) {
                String scheme = intent.getScheme();
                String path = intent.getDataString();                 

                if (scheme.compareTo(ContentResolver.SCHEME_FILE) == 0) {

                    try {
                        InputStream inputStream = getContentResolver().openInputStream(uri);
                        System.out.println("InputStream loaded");
                    } catch (FileNotFoundException e) {
                        System.out.println("InputStream not loaded");
                        e.printStackTrace();
                    }    
                }
            }
        }
    }

字符串对象 path 的值为 file:///storage/emulated/0/Download/prova.json.

主要问题是,当我尝试加载文件时,它会抛出一个异常,提示该文件不存在,即使它确实存在。

再次感谢大家!

因此您要阅读的 json 在设备存储上,因此您需要在您的清单中启用以下权限

这将使旅游应用程序能够在应用程序上下文之外读取设备上的文件