有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正在SD卡上检索文件,路径为:“/document/primary:…”

我正在尝试读取SD卡上CSS文件的内容

我正在从操作中选择文件:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType("text/css");
                    startActivityForResult(intent, 1);

在这里,我抓住了这条路:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
            SharedPreferences sharedPref = PreferenceManager
                    .getDefaultSharedPreferences(getActivity().getApplicationContext());
            SharedPreferences.Editor editor = sharedPref.edit();

            if (requestCode == 1) {
                if(resultCode == Activity.RESULT_OK){
                    Log.d("FilePicker", data.getData().toString());
                    editor.putString("custom_style_file", data.getData().getPath());
                    editor.commit();


                }
                if (resultCode == Activity.RESULT_CANCELED) {
                    //Write your code if there's no result
                }
            }
        }

我得到以下路径/document/primary:CustomCSS/myCustom.css

然后我尝试用这个函数读取文件的内容:

 public static String readFromSDcard(String path) {
        File sdcard = Environment.getExternalStorageDirectory();

        //Get the text file
        File file = new File(sdcard, path);

        //Read text from file
        StringBuilder text = new StringBuilder();

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
            }
            br.close();
        }
        catch (IOException e) {
            //You'll need to add proper error handling here
        }

        Log.d("Read from file", text.toString());
        return text.toString();
    }

该函数不返回任何内容,我不确定我在这里做错了什么


共 (1) 个答案

  1. # 1 楼答案

    确保您在清单文件中具有读取存储权限

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />