一旦程序在設備安裝后,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就是我們寫入的文件