Android_文件存储

本文整理资料来自《android开发权威指南》

文件存储中主要有两个方法openFileOutput和openFileInput。

使用文件保存的数据在/data/data/<package name>/file目录中。

1、下面是向文件中写入和读取数据的代码:

public void fileStore()
	{
		try
		{
			//像指定文件写入内容
			OutputStream os = openFileOutput("file.txt", Activity.MODE_PRIVATE);
			String str1 = "《android、ophone开发完全讲义》";
			os.write(str1.getBytes("utf-8"));
			os.close();
			
			//读取文件
			InputStream is = openFileInput("file.txt");
			byte[] buffer = new byte[100];
			int byteCount = is.read(buffer);
			String str2 = new String(buffer,0,byteCount,"utf-8");
			TextView textView = (TextView) findViewById(R.id.text);
			textView.setText(str2);
			is.close();
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


2、读写SD卡中的文件。

代码如下:

//向SD卡保存图片
	public void store_Image(View view)
	{
		try
		{
			//将创建用于将图像保存到SD卡上的FileOutputStream对象
			FileOutputStream fos = new FileOutputStream(android.os.Environment.getExternalStorageDirectory()+"/image.jpg");
			//打开assets目录中的image.jpg文件,并返回InputStream对象
			InputStream is = getResources().getAssets().open("image.jpg");
			//定义一个byte数组,用于保存每次向SD卡中文件写入的数据,最多8k
			byte[] buffer = new byte[8192];
			int count = 0;
			//循环写入数据
			while ((count = is.read(buffer))>=0)
			{
				fos.write(buffer,0,count);
			}	
			fos.close();
			is.close();
			Toast.makeText(this, "已成功将图像文件写入SD卡上", Toast.LENGTH_LONG).show();
		} catch (Exception e)
		{
			// TODO: handle exception
		}
	}
	//读取SD卡图片
	public void read_Image(View view)
	{
		//指定SD卡中的图像文件名
		String fileName = android.os.Environment.getExternalStorageDirectory()+"/image.jpg";
		//判断是否存在
		if(!new File(fileName).exists())
		{
			Toast.makeText(this, "还没人往SD卡写入数据", Toast.LENGTH_SHORT).show();
			return;
		}
		ImageView imageView = (ImageView) findViewById(R.id.image);
		try
		{
			FileInputStream fis = new FileInputStream(fileName);
			//从文件的输入流装载bitmap
			Bitmap bitmap = BitmapFactory.decodeStream(fis);
			//将图像显示出来在ImageView上
			imageView.setImageBitmap(bitmap);
			try
			{
				fis.close();
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

在默认情况下,是不允许对SD卡中写文件。需要在androidManifest.xml中加入以下权限:

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


运行效果为:


如需源码

请通过链接下载:

http://download.csdn.net/download/zlfxy/5097159

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值