关于Android“外部存储用户信息”代码注释,请问有知道的吗?

public void onClick(View v) {
File sdPath = Environment.getExternalStorageDirectory();
File f = new File(sdPath, "data.txt");
switch (v.getId()) {
case R.id.btn_save:
FileOutputStream fos;
String saveinfo = et_info.getText().toString();
try {
fos = new FileOutputStream(f);
fos.write(saveinfo.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "数据保存成功", 0).show();
break;
case R.id.btn_read:
String content = "";
try {
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
content = new String(buffer);
fis.close();
// BufferedReader br = new BufferedReader(new InputStream(fis)));
// br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "保存的数据是:" + content, 0).show();
break;
default:
break;
}
}

慕尼黑8549860
浏览 116回答 1
1回答

慕田峪7331174

public void onClick(View v) {//获取产生点击事件的View的IDswitch (v.getId()) {case R.id.btn_save://当ID为保存按钮的ID//获取EditText中的内容(去除空格)String saveinfo = et_info.getText().toString().trim();FileOutputStream fos;try {//将内容写入data.txt中,模式是写在原内容尾处。fos = openFileOutput("data.txt", Context.MODE_APPEND);//saveinfo 转化为字节流并通过fos写入对应文件中fos.write(saveinfo.getBytes());fos.close();//关流} catch (Exception e) {e.printStackTrace();}//在屏幕上产生ToastToast.makeText(MainActivity.this, "数据保存成功", 0).show();break;case R.id.btn_read://当ID为读按钮的ID时String content = "";//初始化contenttry {//创建文件读取流FileInputStream fis = openFileInput("data.txt");byte[] buffer = new byte[fis.available()];//新建byte数组,并设置大小。fis.read(buffer);//通过流写入数组content = new String(buffer);//给content初始化赋值} catch (Exception e) {e.printStackTrace();}Toast.makeText(MainActivity.this, "保存的数据是:" + content, 0).show();break;default://以后ID都不是时,不采取操作。break;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android