我正在尝试读取位于我的 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/