android 将对象写入SD卡中

本文介绍如何使用Java将对象保存和从SD卡中读取对象,包括具体方法实现和必要的权限设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇文章中介绍了如何将对象保存在本地,这篇文章主要介绍如何将对象保存在SD卡中:


有了上一篇文章的基础,这里我只用介绍两个方法就OK了。


1. 将对象写入SD卡中

<span style="white-space:pre">	</span>/**
	 * @function 将一个对象保存到SD卡中
	 * @author D-light
	 * @time 2014-07-23
	 * @param String name
	 * @return void
	 */
	private void saveObject2SD(String path){
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		File dir = Environment.getExternalStorageDirectory();
		File file = new File(dir, path);
		try {
			fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(sod);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (oos != null) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


2. 从SD卡中取得对象

<span style="white-space:pre">	</span>/**
	 * @function 从SD卡中读取保存的对象
	 * @author D-light
	 * @time 2014-07-23
	 * @param String name
	 * @return Object
	 */
	private Object getObjectFromSD(String path){
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		File dir = Environment.getExternalStorageDirectory();
		File file = new File(dir, path);
		try {
			fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			return ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (ois != null) {
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}





根据上一篇文章的介绍,其实不难得到我们的结果:

还要加上权限:

<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值