【问题标题】:Android read text file and store into variable based on first wordAndroid根据第一个单词读取文本文件并存储到变量中
【发布时间】:2018-11-12 12:42:36
【问题描述】:

我正在做一个阅读文本文件的练习,我将数据读取并存储到一个字符串数组对象中。一个 ArrayList 数据应该有照片、标题、网站和日期。文本文件如下所示:

photo:android_pie
title:Android Pie: Everything you need to know about Android 9
website:https://www.androidcentral.com/pie
date:20-08-2018
photo:oppo
title:OPPO Find X display
website:https://www.androidpit.com/oppo-find-x-display-review
date:25-08-2018
photo:android_pie2
title:Android 9 Pie: What Are App Actions & How To Use Them
website:https://www.androidheadlines.com/2018/08/android-9-pie-what-are-app- 
actions-how-to-use-them.html
date:16-09-2018

我正在尝试将它们拆分并存储到一个字符串数组中,这是我的对象类的一个实例:

 private List<ItemObjects> itemList;

这是我的对象类的构造函数:

    public ItemObjects(String photo, String name, String link, String date) {
    this.photo = photo;
    this.name = name;
    this.link = link;
    this.date = date;
}

我试过了,但是“:”分隔符没有像我想要的那样分隔它:

                while ((sItems = bufferedReader.readLine()) != null) {
                if (!sItems.equals("")) {
                    String[] tmpItemArr = sItems.split("\\:");

                    listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
                }
            }

这样做的最佳方法是什么?我尝试使用 for 循环,它在第三行停止并将下一个添加为新数据。有几种在线方法,但有些方法非常复杂,我无法理解。

【问题讨论】:

    标签: java arrays bufferedreader


    【解决方案1】:

    问题在于您对同时使用 split 函数和 BufferReader 的理解。 通过使用 readline 函数,您只读取一行,因此您的拆分只会拆分第一行,您需要读取前 4 行然后添加项目。

      int count = 0;
      String[] tmpItemArr = new String[4];
      while ((sItems = bufferedReader.readLine()) != null) {
            if (!sItems.equals("")) {
                tmpItemArr[count] = sItems.split(":")[1];
                count++;
                if (count > 3) {
                    listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
                    count = 0;
                }
            }
        }
    

    【讨论】:

    • 所以逻辑是,sItems.split(":")[1]; 读取“:”分隔符之后的任何内容?对于文本文件 Website: https://www.f..... 中的行,它不会在 https 处拆分“:”吗?
    • 使用“;”分割实体更好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多