【问题标题】:Byte array isn't stored inside object in Android?字节数组不存储在 Android 的对象中?
【发布时间】:2021-07-16 06:19:03
【问题描述】:

我创建了一个 android 应用程序,它应该将用户配置文件存储在设备上的本地文件中。因此,我有一个带有属性名称、地址和图像的对象“配置文件”。属性名称和地址已存储在 den 配置文件中。属性图像是通过来自 Web 服务器的异步任务加载的(这也可以)。在 asynctask 中,我正在调用一个将图像添加到配置文件的方法:

// userProfile is an Object of type Profile
userProfile.setImage(byte_array_image);
// Writing it to file
FileOutputStream fos = activity.openFileOutput("profile", Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
Log.e("Image:",""+userProfile.getImage()); // returns the byte array
os.writeObject(userProfile);
os.close();
fos.close();

然后我尝试通过 openFileInput 读取它(应用程序已重新启动)。这可能是我重新启动应用程序的问题吗?我可以读取除仍然为空的图像之外的所有配置文件属性。

Andy 知道我该如何修复它以及导致错误的原因是什么?图像的写入应覆盖文件配置文件。

【问题讨论】:

  • 更好的方法是使用 Picasso 或 Glide 获取图像并缓存它。

标签: android file object storage


【解决方案1】:

你可以通过这个方法从文件中获取ByteArray。

   var bytes: ByteArray = byteArrayOf()

    bytes = readAllBytes(context, file)

    if (bytes.isNotEmpty()) {

        /**
         * encode byteArray and store encrypted data in mFileTemp
         */
        val bos =
                BufferedOutputStream(
                        FileOutputStream(
                                mFileTemp
                        )
                )
        val encodedBytes =
                FileDownloader.encodeFile(yourKey, bytes)
        bos.write(encodedBytes)
        bos.flush()
        bos.close()
    }

readAllBytes()

fun readAllBytes(context:Context, file:File) : ByteArray{

    var bytes: ByteArray = byteArrayOf()

    try {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            bytes = Files.readAllBytes(
                    Paths.get(
                            getRealPath(
                                    context,
                                    Uri.fromFile(file)
                            )
                    )
            )
        }else{
            bytes = readFile1(file)!!
        }
    }catch (e:Exception){
        Log.e(TAG, "readAllBytes exception : ${e.printStackTrace()}" )
    }


    return bytes
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多