我想使用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)
有什么想法吗?谢谢。
答案 0 :(得分:1)
尝试以下示例Straight from the docs!!!
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();
}