1、内部存储,手机内存,是ROM,不是RAM,存储在手机自带的内存中
作用:在手机的内部存储空间,存储程序的私有数据
存储位置:data/data/包名/files/文件名
创建输出,输入流
FileOutputStream fos = openFileOutput(文件名,模式(MODE_PRIVATE));
FileINputStream fis= openfileInput(文件名);
案例一:
public class MainActivity extends Activity {
private EditText etContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etContent = (EditText) findViewById(R.id.et_content);
}
// 保存
public void save(View v) {
String content = etContent.getText().toString();
// 创建输出流,保存文件
// 参数1:文件名
// 参数2:操作模式,选择私有
try {
FileOutputStream fos = openFileOutput("content.txt",
Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
Toast.makeText(this, "保存成功!", 1).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 读取
public void read(View v) {
try {
FileInputStream fis = openFileInput("content.txt");
byte[] b = new byte[fis.available()];
fis.read(b);
String info = new String(b);
etContent.setText(info);
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
案例二:文件名以对话框的形式显示,可以供用户选择读取的是哪个问价中的数据
public class MainActivity extends Activity {
private EditText etContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etContent = (EditText) findViewById(R.id.et_content);
}
public void save(View v) {
String content = etContent.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = sdf.format(new Date()) + ".txt";
try {
FileOutputStream fos = openFileOutput(fileName,
Context.MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void read(View v) {
// 返回文件名的数组
String[] files = fileList();
// 创建适配器
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, files);
// 创建对话框,显示所有的文件名
new AlertDialog.Builder(this).setTitle("请选择")
.setAdapter(adapter, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String fileName = adapter.getItem(which);
try {
FileInputStream fis = openFileInput(fileName);
byte[] b = new byte[fis.available()];
fis.read(b);
fis.close();
String info = new String(b);
etContent.setText(fileName + "--" + info);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).create().show();
}
}
2、外部存储,sdcard