Android开发代码打开文件管理选择文件,获取路径读取修改文件内容

记录一下Android开发中,获取某文件路径的方法。

1.点击按钮,弹出设备自带的文件管理。

public void onClick(DialogInterface dialogInterface, int i) {
                                if (i == 0) {

                                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                    intent.setType("*/*");
                                    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    startActivityForResult(intent, FILE_REQUEST_CODE);

                                } else if (i == 1) {
                                    Intent intent = new Intent(MainActivity.this, MH3300ManagerActivity.class);
                                    startActivity(intent);
                                }
                            }

2.获取返回的文件路径

 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == FILE_REQUEST_CODE) {
            if (data.getData() != null) {
                try {
                    Uri uri = data.getData();
                    String path = UriUtil.getPath(this, uri);
                    String fileType = path.substring(path.indexOf(".") + 1);
                 	if (!fileType.contains("txt")) {
                       //不是想要的txt文件
                        return;
                    }
                    file = new File(path);
                } catch (Exception e) {
                    
                }
            }
        }
    }

3.UriUtil工具类的代码

/**
     * 专为Android4.4设计的从Uri获取文件绝对路径,以前的方法已不好使
     */
    @SuppressLint("NewApi")
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && 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];
                }
            }
            // 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;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    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;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

4.打开文件读取内容

/**
     * 读取数据
     */
    private void hanlerData() {
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GB2312");
            BufferedReader read = new BufferedReader(isr);

            String str;
            int count = 0;
            List<String> nameArr = new ArrayList<>();
            List<String> valueArr = new ArrayList<>();
            while ((str = read.readLine()) != null) {
                Log.i(TAG, "DataHandler: " + str);
                count++;
                String[] arr = str.split("\t");
                for(String s:arr){
                    if(count ==1){
                        s=s.trim();
                        nameArr.add(s);
                    }
                    if(count ==2){
                        s=s.trim();
                        valueArr.add(s);
                    }
                }
            }
            dataList.clear();
            for(int i = 0;i < nameArr.size();i++){
                Data data = new Data();
                data.setName(nameArr.get(i));
                data.setValue(valueArr.get(i));
                dataList.add(data);
            }
            adapter.setDataList(dataList);
            isr.close();
            read.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

5.将字符串写入文件中并保存

public void onClick(View v) {
                try {
                    int permission = ActivityCompat.checkSelfPermission(ManagerActivity.this, "android.permission.WRITE_EXTERNAL_STORAGE");
                    if (permission != PackageManager.PERMISSION_GRANTED) {
                        // 没有写的权限,去申请写的权限,会弹出对话框
                        ActivityCompat.requestPermissions(MH3300ManagerActivity.this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
                    }

                    //写入数据
                    OutputStreamWriter write = null;
                    String str = "123456";
                    BufferedWriter out = null;

                    write = new OutputStreamWriter(new FileOutputStream(file), Charset.forName("GB2312"));
                    out = new BufferedWriter(write,str.length());
                    out.write(str);
                    out.close();
                    ToastUtils.showLong("保存成功 ");
                }
                catch (Exception e){
                    Log.i(TAG,e.getMessage());
                }
            }

你可能感兴趣的:(Android,android,安卓,java,移动开发)