数据存储。
内部存储:存在手机上,外部存储:存在sdcard上。
一、内部存储:
数据的写:
try {
FileOutputStream fos = openFileOutput(filename,
Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(
fos, "UTF-8"); // 将字节流包装成字符流
osw.write(editText.getText().toString());
osw.flush();
fos.flush();
osw.close();
fos.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();
}
数据的读:
try {
FileInputStream fis = openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis,
"UTF-8");
char[] buffer = new char[fis.available()];
isr.read(buffer);
isr.close();
fis.close();
String dataString = new String(buffer);
textView.setText(dataString);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
二:外部存储
File sdcard = Environment.getExternalStorageDirectory();
数据的写:
File myfFile = new File(sdcard, "lb4_25_file.txt");
if (!sdcard.exists()) {
Toast.makeText(getApplicationContext(), "sd卡不可用",
Toast.LENGTH_SHORT).show();
return;
}
try {
myfFile.createNewFile();
FileOutputStream fos = new FileOutputStream(myfFile);
OutputStreamWriter osw = new OutputStreamWriter(
fos, "UTF-8");
osw.write(editText.getText().toString());
osw.flush();
fos.flush();
osw.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
数据的读:
try {
File myfFile = new File(sdcard, "lb4_25_file.txt");
FileInputStream fis = new FileInputStream(myfFile);
InputStreamReader isr = new InputStreamReader(fis,
"UTF-8");
char[] buffer = new char[fis.available()];
isr.read(buffer);
isr.close();
fis.close();
String dataString = new String(buffer);
textView.setText(dataString);
} 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();
}