文件存储
保存路径 应用程序的包名下的file
// 保存数据
public void saveData(String saveStr,String saveFileName) {
// 判断SD卡是否可用
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
// TODO
}
FileOutputStream fos = null;
BufferedWriter bw = null;
try {
/**
* 打开文件输出流 需要上下文
* @param name 存储文件的名称
* @param int 保存类型
*/
fos = openFileOutput(saveFileName, Context.MODE_PRIVATE);
// 创建缓冲写入器 BufferedWriter会自动刷新缓冲区
bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(saveStr);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
// 关闭缓冲写入器
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// 读取数据
public String readData(String saveFileName) {
FileInputStream fis = null;
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
// 打开文件输入流
fis = openFileInput(saveFileName);
// 创建缓冲读取器
br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line=br.readLine())!=null){
// 每次读取一行并将其拼接起来
sb.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br!=null){
try {
// 关闭缓冲读取器
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public void myClick(View view) {
// 获取sd卡数据大小
File file = Environment.getExternalStorageDirectory();
long totalSpace = file.getTotalSpace();
long usableSpace = file.getUsableSpace();
// import android.text.format.Formatter;
String s = Formatter.formatFileSize(this, totalSpace);
String s1 = Formatter.formatFileSize(this, usableSpace);
Log.e("总大小", "=" + s);
Log.e("可用空间", "=" + s1);
}
SharePreference
public void getSp(){
SharedPreferences sp = getSharedPreferences("spFileName", Context.MODE_PRIVATE);
String s = sp.getString("留言", "没有读取到");
mEditText.setText(s);
}
public void saveSp(){
SharedPreferences sp = getSharedPreferences("spFileName", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putBoolean("是吗",true);
edit.putInt("音量大小",20);
edit.putString("留言","暂时不在家");
// 异步提交(推荐)
edit.apply();
// 同步提交
//edit.commit();
}