---恢复内容开始---

最近在研究assets文件夹的一些属性跟使用方法。根据网上一些文章、实例做一下汇总,拿出来跟大家分享下,有不足的地方还请多多指教。

 

首先了解一下assets是干什么用的,assets英文单词的表面意思是资产、资源,顾名思义,这个文件夹下放的肯定是一些资源文件,而且 assets 文件夹是存放不进行编译加工的原生文件,即该文件夹里面的文件不会像 xml, java 文件被预编译,可以存放一些图片,html,js, css 等文件。assets文件夹下的文件不会被映射到R.java中,访问的时候要用到AssetManager类。

可以通过以下方式获取输入流来进行写操作:

AssetManager am = null;

am = getAssets(); 

InputStream in = am.open("filename"); 

 关于这个文件路径即filename  本来想上图说明的,奈何插入不了图片,所有就拿文字简单说一下。

现在assets文件夹下有一个images文件夹,iamges文件夹下有一张名为large.jpg 的图片。

filename=images/large.jpg

 

下面上代码具体看一下是怎么引用的(亲测好使)。这段代码实现的功能是将large.jpg复制到路径为/mnt/sdcard/Imagexiang/a.jpg上面 ,纸上得来终觉浅,绝知此事要躬行嘛。

 

 

 

 

package xiang.assetsdemotest;

 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.res.AssetManager;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager assetManager=getAssets();
InputStream asset = null;//用来获取从assets文件夹下的输入流
OutputStream out = null;//输出流,用来复制图片
BufferedInputStream bis=null;//缓存输入流
BufferedOutputStream bos=null;//缓存输出流
try {
asset=assetManager.open("images/large.jpg");
bis=new BufferedInputStream(asset);
out=new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/Imagexiang/a.jpg");
bos=new BufferedOutputStream(out);
byte ima[]=new byte[1024];
int len;
while((len=bis.read(ima))!=-1)
{
bos.write(ima, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if(bos!=null)
{
bos.close();
}
if(out!=null)
{
out.close();
}
if(bis!=null)
{
bis.close();
}
if(asset!=null)
{
asset.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@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;
}
}

 奥 还有一点:

GoogleAndroid系统处理Assert有个bug,在AssertManager中不能处理单个超过1MB的文件,不然会报异常。