java - 使用此路径检索 SD 卡上的文件 : "/document/primary:..."

标签 java android

我正在尝试读取位于我的 SDCARD 上的 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();
    }

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

最佳答案

 //You'll need to add proper error handling here

如果你这样做,你就会明白为什么你的函数什么也不返回。

例如:

 text.append("IOException: " + e.getMessage() + "\n");

你的路径:

 /document/primary:CustomCSS/myCustom.css

这不是文件系统路径,而是内容提供程序路径。

因此,获取一个内容解析器,然后让它打开文件的输入流。之后就可以使用常用的代码来读取内容了。

Google 获取 getContentResolver().openInputStream()。

关于java - 使用此路径检索 SD 卡上的文件 : "/document/primary:...",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791048/

相关文章:

android - Eclipse - 在开发时使用组合键 CTRL + Space 显示 android 类?

java - 来自数据库的微调器值给出错误

java - 初级Java : Storing 7 unique random integers in a size 7 array

java - 如何在beanshell中构造Java中的多个对象和JSON数组并查看输出

Java 使用 XPath 解析 iTunes XML 库

php - 服务器聊天应用程序

java - 由于 NullPointerException : Attempt to invoke virtual method HashMap on a null object reference 无法启动 Activity

android - 如何在不创建 repo 的重组副本的情况下将 eclipse 项目导入 Android Studio?

java - 如何在特定情况下避免 OutOfMemory 问题

java - 隐藏服务实现的最佳实践