界面上找到用户名和密码保存成文件
- 不要权限的原因是限制到了程序自己的文件夹
- getCacheDir()和getFilesDir()不同之处在于cache中可能会被删除
public void login(View v){
TextView et_name = (TextView) findViewById(R.id.et_name);
String name = et_name.getText().toString();
//类似的方法找到password
CheckBox cb = findViewById(R.id.cb);
if(cb.isChecked()){//复选框被选中
//getFilesDir()返回的就是data/data/APP_NAME/files
//类似的,getCacheDir(),返回data/data/APP_NAME/cache
File file = new File(getFilesDir(), "info.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write((name+password).getBytes());
fos.close();
}
//创建toast并显示
Toast.makeText(this, "登陆成功", Toast.LENGTH_SHORT).show();
}
public void login(View v){
//用系统给的API直接返回流,文件路径默认为files下
FileOutputStream fos = openFileOutPut("fileName",MODE_APPEND);//MODE_PRIVATE一样权限
}
Activity出现时回写到框内
- 要在OnCreate时调用
public void readAccount(){
File file = new File(getFilesDir(), "info.txt");
if(file.exists()){
FileInputStream fis = new FileInputStream(file);
//字符流转为字节流
BufferedReader br = new BufferReader(new InputSteamReader(fis));
String text = br.readLine();
TextView tv = (TextView) findViewById(R.id.tv_usrname);
tv.setText(text); //数据回写到输入框
}
}
外部存储空间读写文件
- 2.2之前,sd卡路径是sdcard
- 4.3之前,sd卡的路径是mnt/sdcard
- 之后都是storage/sdcard
- 现在很多厂商都乱改目录,最好用系统API
- 写sdcard需要权限
- 读在4.0之后用户可选,之前一般不需要权限
<uses-permission android:name="android.permission.WRITE_EXTERNANL_STORAGE"/>
//sdcard的路径回写数据,sd卡关键代码
public void login(View v){
//SD卡状态:MEDIA_REMOVED 没有SD卡
// MEDIA_MOUNTED SD可用
if(Environment.getExternalStorageState().equals(Enviroment.MEDIA_MOUNTED)){
File file = new File(Environment.getExternalStorageDirctory());
}
}
计算sd卡的空间
- 区块大小*区块个数=空间(字节单位)
- 字节转换为MB
public void write(){
File file = Environment.getExternalStorageDirectory();
//获取sd卡所有状态
StatFs stat = new StatFs(file.getPath());
long blockSize = stat.getBlockSizeLong();
long totalBlocks = stat.getBlockCountLong();
long availBlocks = stat.getAvailableBlocksLong();
String size = Formatter.formatFileSize(this, availBlocks*blockSize);
//write size 到TextView即可
}
查看系统API与快速定位代码位置
- 选中界面上的文字关键信息,在代码中搜寻