手机内部文件file存储学习笔记

1.说明:

>应用运行需要的一些较大的数据或图片可以用文件保存到手机内部

>文件类型: 任意

>数据保存的路径:/data/data/projectPackage/files/

>可以设置数据只能是当前应用读取,而别的应用不可以

>应用卸载时会删除此数据


2.相关API

1)读取文件

> FileInputStream fis = openFileInput("logo.png");

2)保存文件

> FileOutputStream fos = openFileOutput("logo.png", Context.MODE_PRIVATE);

3)得到files文件夹对象

> File filesDir = getFilesDir();

4)操作assets下的文件

>得到AssetManager : context.getAssets();

>读取文件 : InputStream open(filename);

5)加载图片文件

> Bitmap BitmapFactory.decodeFile(String pathName)


3.相关代码

(其中为了方便用throw,应该用try-catch处理)

public class IfActivity extends Activity {

	private ImageView iv_if;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_if);
		iv_if = (ImageView) findViewById(R.id.iv_if);
	}

	public void save(View v) throws IOException {
		// 1.得到InputStream--> 读取assets下的logo.png
		// 得到AssetManager
		AssetManager manager = getAssets();
		// 读取文件
		InputStream is = manager.open("logo.png");
		// 2.得到OutputStream--> /data/data/packageName/files/logo.png
		FileOutputStream fos = openFileOutput("logo.png", Context.MODE_PRIVATE);
		// 3.边读边写
		byte[] buffer = new byte[1024];
		int len;
		while ((len = is.read(buffer)) != -1) {
			fos.write(buffer, 0, len);
		}
		// 关闭流
		fos.close();
		is.close();
		// 4.提示
		Toast.makeText(this, "保存完成", 0).show();

	}

	public void read(View v) {
		// 1.得到图片文件的路径
		// /data/data/packageName/files
		String filesPath = getFilesDir().getAbsolutePath();
		String imagePath = filesPath + "/logo.png";
		// 2.读取加载图片文件得到bitmap对象
		Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
		// 3. 将其设置到imageView中显示
		iv_if.setImageBitmap(bitmap);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值