首页 > 代码库 > 非常标准的将数据保存到file并从file中读取数据。
非常标准的将数据保存到file并从file中读取数据。
字符流:Reader(读) Writer(写)
字节流:InputStream(读数据) OutputStream(写数据)
1,字节流
InputStream(读),OutputStream(写)
2,字符流
Reader(读),Writer(写)
结论:只要是处理纯文本数据,就要优先考虑使用字符流,除此之外都用字节流。
向文件中写入内容
try {
FileOutputStream fos = openFileOutput(INTERNAL_FILENAME , MODE_APPEND);
fos.write("张三\n".getBytes());
// String 的getBytes()方法用于将String==>byte[]
fos.write("89\n".getBytes());
fos.close();
Toast.makeText(this, "写入成功!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
show.setText("写入失败!");
}
默认将info.txt保存的位置为:data/data/包名/files/info.txt
读取的时候也是默认去data/data/包名/files目录下去读取具体的文件,如下:
try {
FileInputStream fis = openFileInput(INTERNAL_FILENAME);
BufferedReader br = new BufferedReader(new InputStreamReader(fis , "utf-8")); //读取行的操作
String content = "";
String line;
while((line = br.readLine()) != null) {
content += line + "\n";
}
br.close();
fis.close();
show.setText(content);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "读取数据失败!", Toast.LENGTH_LONG).show();
}
写一个User类,如下:
public class User {
private String name;
private long date;
private int count;
public User(String name, long date, int count) {
super();
this.name = name;
this.date = date;
this.count = count;
}
public User(String name, int count) {
super();
this.name = name;
this.count = count;
this.date = System.currentTimeMillis();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "User [name=" + name + ", date=" + date + ", count=" + count
+ "]";
}
public String writeInfo() {
return name+","+date+","+count;
}
}
点击一次加入用户按钮,向文件中加入一条数据,如下:
InternalStorageTool.appendInfo(this, new User("bb" , 3));
下面是加入的方法
// 追加用户信息
public static boolean appendInfo(Context context , User user) {
try {
FileOutputStream fos = context.openFileOutput(Const.IN_FILENAME, Context.MODE_APPEND) ;
//这里有追加的权限,Context.MODE_APPEND
fos.write((user.writeInfo() + "\n").getBytes());
//这里转换成字节写入
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
点击某按钮读取所有用户的数据
// 读取所有用户信息
public static List<User> readAllInfo(Context context) {
try {
FileInputStream fis = context.openFileInput(Const.IN_FILENAME);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "utf-8"));
List<User> users = new ArrayList<User>();
String line;
while((line = br.readLine()) != null) {
users.add(parse(line));
}
fis.close();
br.close();
return users;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Parse()方法如下:
private static User parse(String info) {
String[] infoes = info.split(",");
long date = Long.parseLong(infoes[1]);
int count = Integer.parseInt(infoes[2]);
return new User(infoes[0] , date , count);
}