由于assets和res下的文件都只可以读不可以写,那么在程序初始化后,将后期需要使用并且需要修改的文件复制到SD卡。下面代码提供一个工具类,将assets下的任意资源复制到SD卡下。

assets下的资源如下图:

下面是工具类: 
AssetsCopyTOSDcard .java

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment; public class AssetsCopyTOSDcard {
Context context; public AssetsCopyTOSDcard(Context context) {
super();
this.context = context;
} /**
* @param context
* @param assetpath asset下的路径
* @param SDpath SDpath下保存路径
*/
public void AssetToSD(String assetpath,String SDpath ){ AssetManager asset=context.getAssets();
//循环的读取asset下的文件,并且写入到SD卡
String[] filenames=null;
FileOutputStream out = null;
InputStream in=null;
try {
filenames = asset.list(assetpath);
if(filenames.length>0){//说明是目录
//创建目录
getDirectory(assetpath); for(String fileName:filenames){
AssetToSD(assetpath+"/"+fileName, SDpath+"/"+fileName);
}
}else{//说明是文件,直接复制到SD卡
File SDFlie=new File(SDpath);
String path=assetpath.substring(0, assetpath.lastIndexOf("/"));
getDirectory(path); if(!SDFlie.exists()){
SDFlie.createNewFile();
}
//将内容写入到文件中
in=asset.open(assetpath);
out= new FileOutputStream(SDFlie);
byte[] buffer = new byte[1024];
int byteCount=0;
while((byteCount=in.read(buffer))!=-1){
out.write(buffer, 0, byteCount);
}
out.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
out.close();
in.close();
asset.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
//分级建立文件夹
public void getDirectory(String path){
//对SDpath进行处理,分层级建立文件夹
String[] s=path.split("/");
String str=Environment.getExternalStorageDirectory().toString();
for (int i = 0; i < s.length; i++) {
str=str+"/"+s[i];
File file=new File(str);
if(!file.exists()){
file.mkdir();
}
} }
}

MainActivity .java

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String path="aaa/a1.txt";
AssetsCopyTOSDcard assetsCopyTOSDcard=new AssetsCopyTOSDcard(getApplicationContext());
assetsCopyTOSDcard.AssetToSD(path,Environment.getExternalStorageDirectory().toString()+"/"+path);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
   测试路径:
aaa
Aaa/bbb
Aaa/bbb/ba.txt
Aaa/a1.txt

在编程过程中遇到的两个问题:

open failed: ENOENT (No such file or directory)
open failed: EISDIR (Is a directory)

错误修改

if(!SDFlie.exists()){
SDFlie.createNewFile();
}
//将内容写入到文件中
in=asset.open(assetpath);
out= new FileOutputStream(SDFlie);
byte[] buffer = new byte[1024];
int byteCount=0;
while((byteCount=in.read(buffer))!=-1){
out.write(buffer, 0, byteCount);
}
out.flush();

修改为:

if(!SDFlie.exists()){
SDFlie.createNewFile();
//将内容写入到文件中
in=asset.open(assetpath);
out= new FileOutputStream(SDFlie);
byte[] buffer = new byte[1024];
int byteCount=0;
while((byteCount=in.read(buffer))!=-1){
out.write(buffer, 0, byteCount);
}
} out.flush();

因为当文件存在时,不复制。不修改的情况下,out.close();会报空指针异常。

finally{
try {
out.close();
in.close();
asset.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }

修改为:

finally{
try {
if(out!=null){
out.close();
out=null;
}
if(in!=null){
in.close();
in=null;
}
/**
* 关闭报错,java.lang.RuntimeException:
* Unable to start activity ComponentInfo
* {com.example.wealth/com.example.wealth.UI.main}:
* java.lang.RuntimeException: Assetmanager has been closed
*/
// if(asset!=null){
// asset.close();
// asset=null;
// }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

转: https://blog.csdn.net/qq_17326933/article/details/48450487

assets下的文件复制到SD卡的更多相关文章

  1. Android 访问assets下的文件

    assets下经常可以放一些比较大的资源,对于这些资源我们如何访问. 步骤 1.获取AssetManager. AssetManager am = getResources().getAssets() ...

  2. Android 下载文件及写入SD卡

    Android 下载文件及写入SD卡,实例代码 <?xml version="1.0" encoding="utf-8"?> <LinearL ...

  3. Android 将文件保存到SD卡中

    ①写文件到sd卡中需要获得权限,在AndroidManifest.xml中添加如下权限: <uses-permission android:name="android.permissi ...

  4. [置顶] Android学习系列-把文件保存到SD卡上面(6)

    Android学习系列-把文件保存到SD卡上面(5) 一般多媒体文件,大文件需要保存到SD卡中.关键点如下: 1,SD卡保存目录:mnt/sdcard,一般采用Environment.getExter ...

  5. Android项目使用Assets下的文件

    Android项目在编译时,Assets下文件不被编译. Assets下的文件除了 html文件可以直接在项目中使用外,其他的文件都需要做处理滴. 在项目中使用方法:        使用流读取.   ...

  6. android 将项目下的数据库拷贝到sd卡中

    /** * 将项目下的数据库拷贝到sd卡中 */ public static boolean copyDbToSdCard() { FileInputStream fis = null; FileOu ...

  7. asserts文件存到外部SD卡里

    package com.example.wang.testapp3; import android.content.res.AssetManager; import android.graphics. ...

  8. C# 把一个文件夹下所有文件复制到另一个文件夹下 把一个文件夹下所有文件删除(转)

    C# 把一个文件夹下所有文件复制到另一个文件夹下   public static void CopyDirectory(string srcPath, string destPath) { try { ...

  9. Android程序函数 将assets文件夹下的文件复制到手机的sd卡中(包括子文件夹)

    最近在做个功能是将asset文件夹下的所有文件(包括子文件)全部拷贝出来到指定目录下.所用的方法无非是用AssetManager.但是这里 有个问题是也要讲子文件夹和子文件都要拷贝出来.到网上Goog ...

随机推荐

  1. 最大流:Dinic算法

    蒟蒻居然今天第一次写网络流 我太弱啦! 最大流问题有很多解法 虽然isap常数巨小 但是连dinic都写挂的本蒟蒻并不会orz 那么我们选用比较好实现的dinic来解决最大流问题 来一段定义:    ...

  2. web中icon 图标问题

    每个页面都会引入 icon 小图标,下面说下它的用法 一.icon使用 icon的引入方式,与css外部引入方式类似,需要在头部引入, 即: <link rel="shortcut i ...

  3. django生产环节部署

    在linux下安装mysql yum install mysql-server mysql -u root(安装完后,你的root账户是没有密码的.所以你可以直接使用这条命令,就可以登陆控制台了) 如 ...

  4. centos7 快速安装 mariadb(mysql)

    从最新版本的linux系统开始,默认的是 Mariadb而不是mysql! 使用系统自带的repos安装很简单: yum install mariadb mariadb-server systemct ...

  5. nltk 的分词器punkt: ssl问题无法下载

     报错: LookupError: ********************************************************************** Resource pu ...

  6. 搭建SpringCloud-Eureka 注册中心以及服务提供与调用 快速了解 SpringCloud-Eureka

    原文地址:  搭建SpringCloud-Eureka 注册中心以及服务提供与调用   纸上得来终觉浅,绝知此事要躬行啊~果然看着很easy,自己搞起来就是各种坑~各位看官,容我慢慢道来~ 关于spr ...

  7. HTTPS之acme.sh申请证书

    1.关于let's encrypt和acme.sh的简介 1.1 let's encrypt Let's Encrypt是一个于2015年三季度推出的数字证书认证机构,旨在以自动化流程消除手动创建和安 ...

  8. ConcurrentHashMap代码解析

    ConcurrentHashMap (JDK 1.7)的继承关系如下: 1. ConcurrentHashMap是线程安全的hash map.ConcurrentHashMap的数据结构是一个Segm ...

  9. Python对List中的元素排序

    首先定义一个compare函数: def compare(sf1, sf2): if (sf1.value > sf2.value): return -1; elif (sf1.value == ...

  10. 我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=i5j7gwrxj9x5

    我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=i5j7gwrxj9x5