android 保存 parcelable对象,不是说parcelable对象不适合保存在磁盘上吗,
时间: 2024-06-09 18:05:01 浏览: 7
Parcelable 对象确实不适合直接保存在磁盘上,因为它们是为了在内存中高效传输而设计的。但是,您可以将 Parcelable 对象转换为字节数组,然后将字节数组保存到磁盘上。这可以通过以下步骤完成:
1. 将 Parcelable 对象转换为字节数组。您可以使用 Android 提供的 Parcel 类来执行此操作,如下所示:
```java
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Parcel parcel = Parcel.obtain();
parcel.writeParcelable(yourParcelableObject, 0);
byte[] bytes = byteArrayOutputStream.toByteArray();
```
2. 将字节数组保存到磁盘上。您可以使用 Android 提供的文件系统 API 来执行此操作,如下所示:
```java
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
fileOutputStream.write(bytes);
fileOutputStream.close();
```
3. 从磁盘中读取字节数组,并将其转换回 Parcelable 对象。您可以使用以下代码执行此操作:
```java
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
Parcel parcel = Parcel.obtain();
parcel.unmarshall(bytes, 0, bytes.length);
parcel.setDataPosition(0);
YourParcelableObject yourParcelableObject = parcel.readParcelable(YourParcelableObject.class.getClassLoader());
```
请注意,这种方法仅适用于 Parcelable 对象较小且不包含大量数据的情况。如果 Parcelable 对象很大或包含大量数据,则最好使用其他序列化方法,例如 JSON 或 protobuf。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)