- 文件存储
Context类提供了一个方法:openFileOutput(),默认存储位置在/data/data/packagename/files/目录下
第一个参数是文件名,不包含路径,第二个参数是模式:MODE_PRIVATE和MODE_APPEND
private void saveData() {
String data = mEditText.getText().toString();
BufferedWriter bufferedWriter = null;
try {
FileOutputStream fileOutputStream = openFileOutput("hello", MODE_APPEND);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取文件数据:openFileInput()
private void load() {
FileInputStream fileInputStream = null;
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
fileInputStream = openFileInput("hello");
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
} finally {
{
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(MainActivity.this,stringBuilder,Toast.LENGTH_SHORT).show();
}
- SharedPreferences存储
存储位置:/data/data/包名/shared_prefs/目录下,以xml格式存储
参数1:文件名,参数2:模式
SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("key","value");
edit.apply();// edit.commit();
- SQLite存储