一旦程序在设备安装后,data/data/包名/ 即为内部存储空间,对外保密。
Context提供了2个方法来打开输入、输出流
FileInputStream openFileInput(String name)
FileOutputStream openFileOutput(String name, int mode)
public class MainActivity extends Activity {
private TextView show;
private EditText et;
private String filename = "test";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView) findViewById(R.id.show);
et = (EditText) findViewById(R.id.et);
findViewById(R.id.write).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
//FileOutputStream是字节流,如果是写文本的话,需要进一步把FileOutputStream包装 UTF-8是编码
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
//写
osw.write(et.getText().toString());
osw.flush();
fos.flush();
osw.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
findViewById(R.id.read).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
FileInputStream fis = openFileInput(filename);
//当输入输出都指定字符集编码的时候,就不会出现乱码的情况
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
//获取文件的可用长度,构建一个字符数组
char[] input = new char[fis.available()];
isr.read(input);
isr.close();
fis.close();
String readed = new String(input);
show.setText(readed);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
data/data/packagename/files/test就是我们写入的文件