android uri路径转正常本地图片路径

1.String path = FileUtil2.getPath(this, uri.toString());

2.工具类

public class FileUtil2 {

复制代码
public static void writeContent(String file, String content) {
    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(file, true)));
        out.write(content);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void writeContent2(String fileName, String content, boolean isAppend) {
    try {
        // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
        FileWriter writer = new FileWriter(fileName, isAppend);
        writer.write(content);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("-------------------->Exception:" + e.getMessage());
    }
}


/**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param path    The Uri to query.
 * @author paulburke
 */
public static String getPath(final Context context, final String path) {
    if (TextUtils.isEmpty(path)) {
        return "";
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
        return path;
    }

    Uri uri = Uri.parse(path);


    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];
            }

            // 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;
}

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


//以字符为单位读取文件,常用于读取文本、数字等类型的文件
public static void readFileByChars(String fileName) {
    File file = new File(fileName);
    Reader reader = null;
    try {
        System.out.println("以字符为单位读取文件内容,一次读一个字符:");
        //一次读一个字符
        reader = new InputStreamReader(new FileInputStream(file));
        int tempchar;
        while ((tempchar = reader.read()) != -1) {
            if (((char) tempchar) != '\r') {
                System.out.println((char) tempchar);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        System.out.println("以字符为单位读取文件内容,一次读多个字符:");
        char[] tempchars = new char[30];
        int charread = 0;
        reader = new InputStreamReader(new FileInputStream(fileName));
        //将多个字符读取到字符数组中,charread为一次读取的字符数
        while ((charread = reader.read(tempchars)) != -1) {
            if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != '\r')) {
                System.out.println(tempchars);
                Log.i("tempchars", "===123" + new Gson().toJson(tempchars));
            } else {
                for (int i = 0; i < charread; i++) {
                    if (tempchars[i] == '\r') {
                        continue;
                    } else {
                        System.out.println(tempchars[i]);
                        Log.i("tempchars", "===321" + tempchars[i]);
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//以行为单位读取文件,常用于读取面向行的格式化文件
public static void readFileByLines(String fileName) {
    File file = new File(fileName);
    BufferedReader reader = null;
    try {
        System.out.println("以行为单位读取文件内容,一次读一整行:");
        reader = new BufferedReader(new FileReader(file));
        String tempString = null;
        int line = 1;
        //一次读一行,直到读到null,读取文件结束
        while ((tempString = reader.readLine()) != null) {
            System.out.println("line " + line + ":" + tempString);
            Log.i("tempchars", "===321" + "line " + line + ":" + tempString);
            line++;
        }
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


public static String getStoragePath(Context paramContext, boolean paramBoolean) {
    return ((File) Objects.<File>requireNonNull(paramContext.getExternalFilesDir(null))).getAbsolutePath();
}

}

相关推荐
王夏奇几秒前
python中的__all__ 具体用法
java·前端·python
明湖起风了7 分钟前
mqtt消费堆积
java·jvm·windows
Free Tester24 分钟前
如何判断 LeakCanary 报告的严重程度
java·jvm·算法
大家的林语冰42 分钟前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js
清心歌1 小时前
CopyOnWriteArrayList 实现原理
java·开发语言
jiayong231 小时前
第 8 课:开始引入组合式函数
前端·javascript·学习
田八1 小时前
聊聊AI的发展史,AI的爆发并不是偶然
前端·人工智能·程序员
Java成神之路-1 小时前
通俗易懂理解 Spring MVC 拦截器:概念、流程与简单实现(Spring系列16)
java·spring·mvc
zhanghongbin011 小时前
AI 采集器:Claude Code、OpenAI、LiteLLM 监控
java·前端·人工智能
计算机毕设vx_bysj68691 小时前
【免费领源码】77196基于java的手机银行app管理系统的设计与实现 计算机毕业设计项目推荐上万套实战教程JAVA,node.js,C++、python、大屏数据可视化
java·mysql·智能手机·课程设计