Android - 使用 intent 从 phone 内存中打开文件

Android - open file from phone memory using intent

我正在开发一个应用程序,它将 phone 中的 .txt 文件作为输入并将其打印在 TextView 上,

public class MainActivity extends AppCompatActivity {
Button button;
Intent intent;private StringBuilder text = new StringBuilder();



private InputStream getResources(String s) {
    return null;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = (Button) findViewById(R.id.btn);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("text/plain");
            startActivityForResult(intent, 7);
            Log.v("###", "parent "  + getParent());
        }

    });
} @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String Fpath = data.getDataString();
  //  final String fileName = ""+Fpath;
    Log.v("###", "yo " +Fpath);

    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case 7:

            if (resultCode == RESULT_OK) {
                setContentView(R.layout.activity_main);


                Log.v("###", "hellow");
                setContentView(R.layout.activity_main);
                BufferedReader reader = null;

                try {

                    reader = new BufferedReader(

             new InputStreamReader(getAssets().open("filename.txt")));
                    //change code
                    // do reading
                    String mLine;
                    while ((mLine = reader.readLine()) != null) {
                        text.append(mLine);
                        text.append('\n');
                    }
                } catch (IOException e) {
                    String PathHolder = data.getData().getPath();
                    Toast.makeText(MainActivity.this, PathHolder, Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                } finally {


                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            //log the exception
                        }
                    }

                    TextView output = (TextView) findViewById(R.id.Txt);
                    output.setText((CharSequence) text);

                }
            }
    }
}
}

一切都很好,除了这条线

new InputStreamReader(getAssets().open("filename.txt")));

从 Assets 文件夹中获取文件, 帮助我从我的 phone,

中获取文件

Assets 文件夹中的文件可以正常打开,但我希望它是 phone

中的 select

你可以试试这个方法:

 public static String getMimeType(String url) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
    return type;
}

 public static Uri getFileUri(String filePath) {
    Uri fileUri = null;
    File file = new File(filePath);
    try {
        if (Build.VERSION.SDK_INT >= 24) {
            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        }
        fileUri = Uri.fromFile(file);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileUri;
}

以及意图:

if (path.endsWith(".txt") || path.endsWith(".TXT")) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(getFileUri(path.trim()), getMimeType(path.trim()));
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

        if (intent.resolveActivity(context.getPackageManager()) != null) {
            context.startActivity(intent);
        } else
            Toast.makeText(context, "There is no application available to handle your request!!", Toast.LENGTH_SHORT).show();

    } 

您可以在onActivityResult中获取您从文件管理器中选择的文件路径。

 Uri PathHolder = data.getData();

更新

上一行为您提供了您从存储中选择的文件 的 uri。然后您可以轻松地从该 Uri 获取文件。

刚刚忘记了 getAssets 使用以下方法从文件中读取。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Uri PathHolder = data.getData();
    FileInputStream fileInputStream = null;
    StringBuilder text = new StringBuilder();
    try {
        InputStream inputStream = getContentResolver().openInputStream(PathHolder);
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        String mLine;
        while ((mLine = r.readLine()) != null) {
            text.append(mLine);
            text.append('\n');
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

您的 onActivityResult 略有变化 首先将这段代码粘贴到您的 activity 中。

    public static String getPath(final Context context, final Uri uri) {

            final boolean isKitKat = true;

            // DocumentProvider
            if (DocumentsContract.isDocumentUri(context, uri)) {
                // ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    if ("primary".equalsIgnoreCase(type)) {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }

                    // TODO handle non-primary volumes
                }
                // DownloadsProvider
                else if (isDownloadsDocument(uri)) {

                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(
                            Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                    return getDataColumn(context, contentUri, null, null);
                }
                // MediaProvider
                else if (isMediaDocument(uri)) {
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];

                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }

                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{
                            split[1]
                    };

                    return getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            // MediaStore (and general)
            else if ("content".equalsIgnoreCase(uri.getScheme())) {
                return getDataColumn(context, uri, null, null);
            }
            // File
            else if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }

            return null;
        }
  public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }
 public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
  public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

现在将您的 onActivityResult 更改为此。

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
//                String pickedImage = data.getData().getPath();
                String dataString = getPath(this, Uri.parse(data.getDataString()));
                Log.i(TAG, "onActivityResult: pathholder " + dataString);
                File file = new File(dataString);//
                FileInputStream fis = null;
                Log.i(TAG, "onActivityResult: file " + file.getName());
/**if you get the uri(path) then add this following code that i given below*/
                try {
                    fis = new FileInputStream(file.getAbsolutePath());
                    InputStreamReader isr = new InputStreamReader(fis);
                    BufferedReader bufferedReader = new BufferedReader(isr);
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line).append("\n");

                    }
                    Log.i(TAG, "onActivityResult: pathholder " + sb.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }



            }
        }
    }