美文网首页Android OtherAndroid 进阶之路Android开发
【 Android 】CSV 文件在 Android 开发中的应

【 Android 】CSV 文件在 Android 开发中的应

作者: Tyhoo_Wu | 来源:发表于2018-01-21 13:04 被阅读270次

    Android 从服务器读取数据通常情况下都是读取的 Json 数据,其实 .csv 文件也有同样的效果。本文将围绕两方面进行讲解:① 读取 .csv 文件 ② 将数据写入到 .csv 文件里。

    一、读取 .csv 文件

    .csv文件是可以用 Excel 或者记事本打开和编辑的。先看一个示例文件

    .csv 文件

    ② 读取.csv文件,并显示在 UI 上
    通过示例图,我们需要创建一个bean拿到idnameagegettersetter方法。

    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<TestDataBean> readCsv(String path) {
        ArrayList<TestDataBean> 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文件夹里面
    6.0 之前的系统:

    adb push "文件路径\xxx.csv" /data/data/包名/files/
    

    6.0 之后的系统:

    adb push "文件路径\xxx.csv" /data/user/0/包名/files/
    

    ⑤ 读取.csv文件并显示在 UI 上
    效果图:

    读文件

    示例代码:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        private static final String TAG = MainActivity.class.getSimpleName();
    
        private RecyclerView mRecyclerView;
    
        private List<TestDataBean> mList;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initView();
        }
    
        private void initView() {
            Button mBtnRead = findViewById(R.id.btn_read);
            mRecyclerView = findViewById(R.id.rcv_main);
    
            mBtnRead.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_read:
                    readCsvFile();
                    break;
                default:
                    break;
            }
        }
    
        private void readCsvFile() {
            mList = readCsv(this.getFilesDir().getAbsolutePath() + File.separator + "csv_file" + ".csv");
    
            if (mList.size() > 0) {
                Snackbar.make(mRecyclerView, "Csv 文件读取成功", Snackbar.LENGTH_SHORT).show();
            } else {
                Snackbar.make(mRecyclerView, "Csv 文件读取失败", Snackbar.LENGTH_SHORT).show();
            }
    
            MainAdapter mAdapter = new MainAdapter(this);
    
            mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            mRecyclerView.setHasFixedSize(true);
            mRecyclerView.setAdapter(mAdapter);
    
            mAdapter.setDataList(mList);
        }
    
        private ArrayList<TestDataBean> readCsv(String path) {
            ArrayList<TestDataBean> 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;
        }
    }
    
    public class MainAdapter extends RecyclerView.Adapter<MainAdapter.MainViewHolder> {
    
        private static final String TAG = MainAdapter.class.getSimpleName();
    
        private Context mContext;
    
        private List<TestDataBean> mList = new ArrayList<>();
    
        public MainAdapter(Context context) {
            mContext = context;
        }
    
        public void setDataList(List<TestDataBean> list) {
            mList = list;
    
            Log.d(TAG, "setDataList: " + mList.size());
    
            notifyDataSetChanged();
        }
    
        @Override
        public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_main, parent, false);
            return new MainViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(MainViewHolder holder, int position) {
            holder.tvId.setText(mList.get(position).getId() + "");
            holder.tvName.setText(mList.get(position).getName() + "");
            holder.tvAge.setText(mList.get(position).getAge() + "");
        }
    
        @Override
        public int getItemCount() {
            return mList == null ? 0 : mList.size();
        }
    
        public class MainViewHolder extends RecyclerView.ViewHolder {
    
            TextView tvId, tvName, tvAge;
    
            public MainViewHolder(View itemView) {
                super(itemView);
                tvId = itemView.findViewById(R.id.tv_id);
                tvName = itemView.findViewById(R.id.tv_name);
                tvAge = itemView.findViewById(R.id.tv_age);
            }
        }
    }
    

    代码清晰明了,没有一句多余代码,就不做过多解释了。

    二、写入 .csv 文件

    ① 公开一个写入.csv文件的方法,将数据写入到.csv文件里

    private void writeCsvFile() {
        try {
            File file = new File(this.getFilesDir().getAbsolutePath() + File.separator + "new_csv_file" + ".csv");
            BufferedWriter bw = new BufferedWriter(new FileWriter(file, true));
            // 添加头部名称
            bw.write("id" + "," + "name" + "," + "age");
            bw.newLine();
            for (int i = 0; i < mList.size(); i++) {
                bw.write(mList.get(i).getId() + "," + mList.get(i).getName() + "," + mList.get(i).getAge());
                bw.newLine();
            }
            bw.close();
    
            Snackbar.make(mRecyclerView, "Csv 文件已生成", Snackbar.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    其中mList就是上面读取的数据,代码清晰明了,不做过多解释。

    ② 验证新的.csv文件是否写入成功

    写入文件
    从图中我们可以看到新文件已经生成,我们通过adb pull将文件拉取出来,看看是否真的写入了。

    拉取文件之后打开文件查看内容:


    新的 .csv 文件

    证明写入成功!

    三、使用 Apache Commons CSV 读写 .csv 文件

    ① 导入必要的库

    implementation 'org.apache.commons:commons-csv:1.5'
    

    ② 代码部分

    // 初始化 List
    private List<ApacheBean> mList = new ArrayList<>();
    
    // .csv 文件路径
    String path = getFilesDir().getAbsolutePath() + File.separator + "test_file" + ".csv";
    
    // 读取 .csv 文件
    private void readCsv(String path) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));  // 防止出现乱码
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
            Iterable<CSVRecord> csvRecords = csvParser.getRecords();
            for (CSVRecord csvRecord : csvRecords) {
                ApacheBean apacheBean = new ApacheBean();
                apacheBean.setId(Integer.parseInt(csvRecord.get("id")));
                apacheBean.setName(csvRecord.get("name"));
                apacheBean.setAge(Integer.parseInt(csvRecord.get("age")));
                mList.add(apacheBean);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 写入 .csv 文件
    private void writeCsv() {
        try {
            File file = new File(this.getFilesDir().getAbsolutePath() + File.separator + "new_test_file" + ".csv");
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));  // 防止出现乱码
            // 添加头部
            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT.withHeader("id", "name", "age"));
            // 添加内容
            for (int i = 0; i < mList.size(); i++) {
                csvPrinter.printRecord(
                        mList.get(i).getId(),
                        mList.get(i).getName(),
                        mList.get(i).getAge(),
                        mList.get(i).getCompany(),
                        mList.get(i).getAddress());
            }
            csvPrinter.printRecord();
            csvPrinter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    以上就是.csv文件在Android中的应用。

    相关文章

      网友评论

        本文标题:【 Android 】CSV 文件在 Android 开发中的应

        本文链接:https://www.haomeiwen.com/subject/unjfaxtx.html