首页 > 解决方案 > 当尝试将 byteArray 写入文件时,它会转换 0B png 文件,无法获取有效文件

问题描述

val downloadDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getString(R.string.app_name))

        if (!downloadDir.isDirectory) {
            //Creates directory named by this file
            downloadDir.mkdirs()
        }

        val file = File(downloadDir, fileName)

        try {
            val ostream = FileOutputStream(file)
            ostream.write(imageByteArray)
            ostream.flush()
            ostream.close() }

标签: androidfilekotlin

解决方案


我正在使用以下代码将用户的头像保存在sdcard. 您可以更改代码以满足您的需求:

 public static String copyToAppDirectory(Context c, Uri uri, String personID) throws IOException {

    File src = new File(uri.getPath());
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), BaseConst.AppDir);
    mediaStorageDir = new File(mediaStorageDir, BaseConst.ImageFolder);

    File dst = new File(mediaStorageDir, personID + ".JPG");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            throw new IOException("Cannot create Directory!");
        }
    }
    InputStream in;
    try {
        in = c.getContentResolver().openInputStream(uri);
    } catch (Exception ex) {
        in = new FileInputStream(src);
    }

    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
    return dst.getPath();
}

希望对你有帮助


推荐阅读