Android 从服务器读取数据通常情况下都是读取的 Json 数据,其实 .csv 文件也有同样的效果。本文将围绕两方面进行讲解:① 读取 .csv 文件 ② 将数据写入到 .csv 文件里。
一、读取 .csv 文件
① .csv文件是可以用 Excel 或者记事本打开和编辑的。先看一个示例文件
.csv 文件
② 读取.csv文件,并显示在 UI 上
通过示例图,我们需要创建一个bean拿到id、name、age的getter和setter方法。
public class TestDataBean {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public TestDataBean(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
③ 公开一个读取.csv文件的方法
private ArrayList readCsv(String path) {
ArrayList readerArr = new ArrayList<>();
File file = new File(path);
FileInputStream fileInputStream;
Scanner in;
try {
fileInputStream = new FileInputStream(file);
in = new Scanner(fileInputStream, "UTF-8");
in.nextLine();
while (in.hasNextLine()) {
String[] lines = in.nextLine().split(",");
TestDataBean bean = new TestDataBean(Integer.parseInt(lines[0]), lines[1], Integer.parseInt(lines[2]));
readerArr.add(bean);
}
} catch (Exception e) {
e.printStackTrace();
}
return readerArr;
}
④ 通过adb命令将.csv文件写入到包名下的file文件夹里面<