java - 从文件管理器读取文件
问题描述
我想使用 android 的文件选择器选择一个文件,然后在 EditText 组件中显示它的内容。
我有这种方法,我打开文件管理器并在下载中搜索文件
public void btnSearch(View view){
Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
fileIntent.setType("*/*");
fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(fileIntent,"Seleccione"),FILE_SELECTED_CODE);
} catch (android.content.ActivityNotFoundException ex){
System.out.println( ex.getMessage());
Toast.makeText(this,"Install a File Manager. ", Toast.LENGTH_SHORT).show();
}
}
然后我用这个方法读取文件的内容
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(data == null)
return;
switch (requestCode){
case FILE_SELECTED_CODE:
if(resultCode == RESULT_OK){
Uri uri = data.getData();
String ruta = uri.getPath();
File archivo = new File(ruta);
try {
BufferedReader reader = new BufferedReader(new FileReader(archivo));
String linea = "";
String texto = "";
while((linea = reader.readLine()) != null){
texto += linea;
}
EditText tbxDatos = (EditText) findViewById(R.id.compDatos);
tbxDatos.setText(texto);
} catch(Exception e){
System.out.println( e.getMessage());
}
}
break;
}
super.onActivityResult(requestCode,resultCode,data);
}
但是现在当我从文件选择器中选择文件时出现此异常:
Exception: /document/33 (No such file or directory)
有任何想法吗?谢谢你。
解决方案
直接从文档中试试这个例子!!!
private String readTextFromUri(Uri uri) throws IOException {
InputStream inputStream = getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
fileInputStream.close();
parcelFileDescriptor.close();
return stringBuilder.toString();
}
推荐阅读
- android - 如何显示您的 android 应用程序图标以及复制粘贴菜单
- spring-boot - Spring Boot Validation:如何测试 DTO 对象
- python - 我得到了 ValueError: Input contains NaN, infinity or a value too large for dtype('float64')
- sqlite - CTE 中的 SQLite RANDOM() 函数
- python - li.append(ki) 和 li.append(list(ki)) 的区别?
- yii2 - AppAsset 不包括
- c++ - Visual C++ 断言 - 字符串下标超出范围
- javascript - 导出 redux 减速器时,我收到“TypeError:无法读取未定义的属性‘名称’”
- scala - 从 Doubles 列表中返回 List[Double], Map[String, Double]
- javascript - 是什么让 `async/await` 语句在 ES6 中顺序运行而不是并行运行?