Android复制res/raw目录下的资源到SD卡中

该代码段展示了在Android环境中如何从res/raw资源目录复制文件到指定的存储路径。它首先打开资源,然后检查目标文件夹是否存在,如果不存在则创建,接着读取输入流并将数据写入目标输出流,最后关闭流。
摘要由CSDN通过智能技术生成
private static final String SEPARATOR = File.separator;//路径分隔符

/**
 * 复制res/raw中的文件到指定目录
 *
 * @param context     上下文
 * @param id          资源ID
 * @param fileName    文件名
 * @param storagePath 目标文件夹的路径
 */

public static void copyFilesFromRaw(Context context, int id, String fileName, String storagePath) {
	InputStream inputStream = context.getResources().openRawResource(id);
	File file = new File(storagePath);
	//如果文件夹不存在,则创建新的文件夹
	if (!file.exists()) {
		file.mkdirs();
	}
	readInputStream(storagePath + SEPARATOR + fileName, inputStream);
}

/**
 * 读取输入流中的数据写入输出流
 *
 * @param storagePath 目标文件路径
 * @param inputStream 输入流
 */
public static void readInputStream(String storagePath, InputStream inputStream) {
	File file = new File(storagePath);
	try {
		if (!file.exists()) {
			// 1.建立通道对象
			FileOutputStream fos = new FileOutputStream(file);
			// 2.定义存储空间
			byte[] buffer = new byte[inputStream.available()];
			// 3.开始读文件
			int lenght = 0;
			while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
				// 将Buffer中的数据写到outputStream对象中
				fos.write(buffer, 0, lenght);
			}
			// 刷新缓冲区
			fos.flush();
			// 4.关闭流
			fos.close();
			inputStream.close();
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值