Android [小技巧] CSV文件简单使用

来源:互联网 发布:监控windows 资源命令 编辑:程序博客网 时间:2024/06/13 02:44

在做安卓的时候,可能会遇到要储存一下表型的数据,但是数据量不大,对安全性要求也不高,用数据库稍显累赘,我们就可以使用CSV文件来储存啦。而且CSV是可以用Excel直接打开编辑的,非常方便。

比如我要存下以下数据。

| 水果 | 价格 | 数量 |
| —- | —-: | :—-: |
| 香蕉 | 2 | 5 |
| 苹果 | 1 | 6 |
| 草莓 | 3 | 7 |

那么,我们只要建一个文本就可以存储了:
每一个数据用英文”,”来分隔
data.csv

水果,价格,数量香蕉,2,5苹果,1,6草莓,3,7

接下来是从文件读取

数据读出来后用类暂存起来

Class Fruit{    String mName;    int mPrice;    int mNum;    Fruit(String name, int price, int num){        mName = name;        mPrice = price;        mNum = num;    }}

读取文件的函数

public static ArrayList<Fruit> readCSV(String path) {        ArrayList<Fruit> fruitArr = new ArrayList<>();        File file = new File(path);        FileInputStream fileInputStream;        Scanner in;        try {            fileInputStream = new FileInputStream(file);            //一定要声明为GBK编码,因为默认编码为GBK            in = new Scanner(fileInputStream, "GBK");            //舍弃第一行            in.nextLine();            while (in.hasNextLine()) {                String[] lines = in.nextLine().split(",");                Fruit fruit = new Fruit(lines[0],Integer.parseInt(lines[1]),Integer.parseInt(lines[2]));                fruitArr.add(fruit);            }        } catch (Exception e) {            e.printStackTrace();        }        return fruitArr;    }

这样就得到了一个Fruit的数组。


用函数存数据比较简单就不累赘了,注意加权限就好。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
原创粉丝点击