一、内部存储
内部存储是指将应用程序中的数据以文件方式存储到设备的内部存储空间中(该文件位于data/data/<packagename>/files/目录下),内部存储方式存储的文件被其所创建的应用程序私有,如果其他应用程序要操作本应用程序中的文件,需要设置权限。当创建的应用程序被卸载时,其内部存储文件也随之被删除。
内部存储使用的是Context提供的openFileOutput()方法和openFileInput()方法,通过这两个方法可以分别获取FileOutputStream对象和FileInputStream对象,具体如下:
FileOutputStream openFileOutput(String name,int mode);
FileInputStream openFileInput(String name);
上述两个方法中,openFileOutput()用于打开应用程序中对应的输出流,将数据存储到指定的文件中;openFileInput()用于打开应用程序对应的输入流,用于从文件中读取数据。其中,参数name表示文件名,mode表示文件的操作模式,也就是读写文件的方式,它的取值有4种,具体如下:
MODE_PRIVATE:该文件只能被当前程序读写,默认的操作模式。
MODE_APPEND:该文件的内容可以追加,常用的一种模式。
MODE_WORLD_READABL:该文件的内容可以被其他文件读取,安全性低,通常不使用。
MODE_WORLD_WRITEABLE:该文件的内容可以被其他程序写入,安全性低,通常不使用。
存储数据时,使用FileOutputStream对象将数据存储到文件中的示例代码如下:
String fileName = "data.txt"; //文件名称
String content = "helloworld"; //保存数据
FileOutputStream fos;
try{
fos=openFileOutput(fileName,MODE_PRIVATE);
for=write(content.getBytes());
fos.close();
}catch(Exception e){
e.printStackTrace();
}
上述代码中,分别定义了String类型的文件名data.txt,以及要写入文件的数据helloworld,然后创建FileOutputStream对象,通过该对象将数据helloworld写入到data.txt文件。
取出数据时,使用FileInputStream对象读取数据的示例代码如下:
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();
}
上述代码中,首先通过openFileInput("data.txt")获取到文件输入流对象,然后通过缓冲区buffer存储读取的文件,最后将读取到的数据赋值给String变量。
二、外部存储
使用外部存储设备之前必须使用Environment.getExternalStorageState()方法来确认外部设备是否可用。
向外部设备(SD卡)中存储数据的示例代码如下所示:
String state=Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
File SDPath = Environment.getExternalStorageDirectory();
File file = new File(SDPath,"data.txt");
String data = "HelloWorld";
FileOutputStream fos;
try{
fos = new FileOutputStream(file);
fos.write(data.getBytes());
fos.close();
}catch{
e.printStackTrace();
}
}
从外部设备(SD卡)中读取数据的示例代码如下所示:
String state = Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED)){
File SDPath = Environment.getExternalStorageDirectory();
File file = new File(SDPath,"data.txt");
FileInputSteam fis;
try{
fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String data = br.readLine();
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
读取外部设备中的数据时,同样需要判断外部设备是否可用以及是否具有读取权限。
权限信息:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>