首页 > 解决方案 > 从文件管理器读取文件

问题描述

我想使用 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)

有任何想法吗?谢谢你。

标签: javaandroidandroid-studio

解决方案


直接从文档中试试这个例子!!!

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();
}

推荐阅读