文件存储之读写SD卡中的文件小记

来源:互联网 发布:淘宝网店新手 编辑:程序博客网 时间:2024/06/06 09:46

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;@Overrideprotected 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() {@Overridepublic void onClick(View v) {//android.os.Environment.getExternalStorageDirectory()获取Sd卡的路径    Stringpath =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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});load.setOnClickListener(new OnClickListener() {@Overridepublic 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});}}
记得在
AndroidManifest.xml文件中添加代开读写文件的权限哦

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

效果图如下: