public class MainActivity extends Activity {
final String FILE_NAME = "crazyit.bin";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText et1 = (EditText) findViewById(R.id.edt1);
final EditText et2 = (EditText) findViewById(R.id.edt2);
Button btnWrite = (Button) findViewById(R.id.btnIn);
btnWrite.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
write(et1.getText().toString());
et1.setText("");
}
});
Button btnRead = (Button) findViewById(R.id.btnOut);
btnRead.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
et2.setText(read());
}
});
}
/**
* 写入到/data/data/[包名]/files 路径下
*
* @param content
*/
private void write(String content) {
try {
FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_APPEND);
PrintStream ps = new PrintStream(fos);
ps.println(content);
ps.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* /data/data/[包名]/files 路径下读取文件
*
* @return
*/
private String read() {
try {
FileInputStream fis = openFileInput(FILE_NAME);
byte[] buff = new byte[];
int hasRead = ;
StringBuilder sb = new StringBuilder("");
while ((hasRead = fis.read(buff)) > ) {
sb.append(new String(buff, , hasRead));
}
fis.close();
return sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}