当前位置: 首页 > article >正文

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

}


http://www.kler.cn/a/551056.html

相关文章:

  • 利用爬虫精准获取淘宝商品描述:实战案例指南
  • Python in Excel高级分析:一键RFM分析
  • 美国股市主要指数介绍(Major U.S. Stock Market Indexes):三大股指(中英双语)
  • 基于Flask的艺恩影片票房分析系统的设计与实现
  • 获取所有conda虚拟环境的python版本以及torch版本
  • 在Nodejs中使用kafka(二)partition消息分区策略
  • Hbase 2.2.4 伪分布环境与安装
  • 推荐两个比较好用的流程图js库
  • 计算机网络(3)TCP格式/连接
  • [论文阅读] SeeSR: Towards Semantics-Aware Real-World Image Super-Resolution
  • 【C++游戏开发-五子棋】
  • Unity3D UI菜单与场景切换详解
  • 解决macos安装docker后不能远程连接的问题
  • 使用 Apache PDFBox 提取 PDF 中的文本和图像
  • Linux-GlusterFS
  • Ollama+DeepSeek+Open-WebUi
  • 计算机视觉-OpenCV图像处理
  • lwip的UDP实现
  • 【2024】Wavelet Mixture of Experts for Time Series Forecasting
  • 函数的返回值的使用