Android学习笔记整理(10)--数据存储方式之文件存储

版权声明:本文为博主原创文章,欢迎转载,转载请注明出处。 https://blog.csdn.net/qq_29477223/article/details/80828190

1.文件存储简介

      文件存储是Android中最基本的一种数据存储方式,它与Java中的文件存储类似,都是通过I/O流的形式把数据原封不动的存储到文档中。不同的是,Android的文件存储分为内部存储和外部存储。

2.内部存储

    内部存储是指将应用程序中的数据以文件方式存储到设备的内部存储空间中(该文件位于data/data/<packagename>/files/目录下)

      内部存储使用的是Context提供的openFileOutput()方法和openFileInput方法,通过这两种方法可以分别获取FileOutputStream对象和FileInputStream对象

FileOutputStream openFileOutput(String name, int mode);
FileInputStream openFileInput(String name);

其中,参数name表示文件名,mode表示文件的操作模式,读写方式,取值有4种

  • MODE_PRIVATE:该文件只能被当前程序读写,默认的操作模式
  • MODE_APPEND:该文件的内容可以追加,常用的一种模式
  • MODE_WORLD_READABLE:该文件的内容可以被其他文件读取,安全性低,通常不使用
  • MODE_WORLD_WRITEABLE:该文件的内容可以被其他程序写入,安全性低,通常不适用

openFileOutput()用于打开应用程序中的对应的输出流,将数据存储在指定的文件中

String fileName=""data.txt;  //文件名称
String content="helloworld";  //保存数据
FileOutputStream fos;
try{
    fos=openFileOutput(fileName,MODE_PRIVATE);
    fos.write(content.getBytes());
    fos.close();
}catch(Exception e){
    e.printStackTrace();
}
将数据helloworld写入到data.txt文件

openFIleInput()用于打开应用程序对应的输入流,用于从文件中读取数据

String content="";
FileInputStream fis;
    try{
	fis=openFileInput("data.txt");
	byte[] buffer=new byte[fis.available()];
	fis.read(buffer);
	content=new String(buffer);
    }catch(Exception e){
	e.printStackTrace();
    }

通过缓冲区buffer存储读取的文件,将读取的数据赋值给String变量

3.外部存储

      外部存储是指将文件存储到一些外围设备上(该文件通常位于mnt/sdcard目录下,不同牌子的手机路径可能不同),例如SD卡或者设备内嵌的存储卡,属于永久性的存储方式。

    由于外部存储设备可以被移除、丢失或者其他状态,因此在使用外部设备必须要使用一种方法来确定设备是否可用Environment.getExternalStorageState()。

向SD卡中存储数据

String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
	File SDPath = Environment.getExternalStorageDirectory(); 用于获取SD卡根目录的路径
	File file = new File(SDPath, "data.txt");
	String data = "HelloWorld";
	FileOutputStream fos;
	try {
		fos = new FileOutputStream(file);
		fos.write(data.getBytes());
		fos.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

向SD卡中读取数据

String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
	File SDPath = Environment.getExternalStorageDirectory(); 
	File file = new File(SDPath, "data.txt");
	FileInputStream fis;
	try {
		fis = new FileInputStream(file);
                BufferedReader br=new BufferedReader(new InputStreamReader(fis));
                String data=br.readLine();
		fis.close();
		fos.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}

需要注意的是,Android系统为了保证应用程序的安全性做了相应规定,如果程序需要访问系统的一些关键信息,必须在清单文件中声明权限,否则程序会崩溃,需要在<manifest>节点下配置权限信息。

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

上述代码指定了SD卡具有可写和可读的权限,因此程序可以操作SD卡中的数据



猜你喜欢

转载自blog.csdn.net/qq_29477223/article/details/80828190
今日推荐