Android中用来数据存储的有SharedPreferences,SQLite,文件存储,其中apk中的可以存资源放在SD卡上,Android中可以用FileInputStream FileOutputStream来读写指定路径的文件。
下面是一个例子来体现这一点,我将apk文件中的图像存储到SD卡上然后再把他读出来用ImageView来显示。
首先准备一张图片,将文件放到assets目录中
布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/savebtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/saveSD"
/>
<Button
android:id="@+id/loadbtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/loadSD"
/>
<ImageView
android:id="@+id/imgone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
程序代码
public class SDCardTestActivity extends Activity {
private Button save,load;
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sdcardtest);
save = (Button) findViewById(R.id.savebtn);
load = (Button) findViewById(R.id.loadbtn);
image = (ImageView) findViewById(R.id.imgone);
save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//android.os.Environment.getExternalStorageDirectory()获取Sd卡的路径
String path =android.os.Environment.getExternalStorageDirectory()+"/image.jpg";
try {
//创建用于将图像保存到SD卡上的FileOutputStream对象
FileOutputStream fos = new FileOutputStream(path);
InputStream is = getResources().getAssets().open("fat_po_f01.gif");
byte[] buffer = new byte[8192];
int count =0;
//将图片写到Sd卡中
while ((count=is.read(buffer))>=0)
{
fos.write(buffer, 0, count);
}
fos.close();
is.close();
Toast.makeText(SDCardTestActivity.this, "已将图片保存到sd卡中", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
load.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String filename= android.os.Environment.getExternalStorageDirectory()+"/image.jpg";
if(!new File(filename).exists())
{
Toast.makeText(SDCardTestActivity.this, "亲sd卡中还没有图片哦", Toast.LENGTH_LONG).show();
return ;
}
try {
//创建用于都SD卡的FileInputStream对象
FileInputStream fis = new FileInputStream(filename);
//对流进行解析,创建Bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(fis);
image.setImageBitmap(bitmap);
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
记得在
AndroidManifest.xml文件中添加代开读写文件的权限哦
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
效果图如下: