【问题标题】:Reading CSV file in android and putting it into a Hashmap在android中读取CSV文件并将其放入Hashmap
【发布时间】:2017-03-13 06:26:48
【问题描述】:

我正在尝试将 CSV 文件中的数据添加到列表中。目前我在下面有这段代码,但是每当我尝试运行它时应用程序就会关闭。

private HashMap<String, GeoLocation> loadLocationData() {
    String csvFile = "C:\\Users\\MyName\\Documents\\MyApplication\\app\\src\\main\\res\\raw\\geo_locations.csv";
    String line = "";
    String cvsSplitBy = ",";

    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

        while ((line = br.readLine()) != null) {
            String[] cityloc = line.split(cvsSplitBy);
            locations.put(cityloc[0], new GeoLocation(cityloc[0], Double.parseDouble(cityloc[1]), Double.parseDouble(cityloc[2]), TimeZone.getTimeZone(cityloc[3])));
       }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return locations;
}

我已经询问过有关阅读 CSV 文件的问题,并收到了一份关于它的其他问题列表,但是,在处理完之后,我无法在这里解决我的问题。

我需要做的基本要点是从 CSV 文件中获取该列表,并从中创建一个可以添加到“位置”的列表。

【问题讨论】:

  • Get and Parse CSV file in android 的可能重复项...我不确定C: 在 Android 设备上是否有意义。
  • 如果 CSV 格式错误会怎样?你没有所有的参数(空行)? Double 或 TimeZone 格式不正确?你的函数可以处理这个吗?
  • 您的 Android 设备/模拟器没有 C: 驱动器。
  • "C:\\Users\\MyName\\Documents\\MyApplication\\app\\src\\main\\res\\raw\\geo_locations.csv" 显然是您的路径开发机器。即使您在模拟器中运行该应用程序,您也需要使用模拟设备上实际存在的路径。您可以查看处理应用程序资源以及如何访问它们的 Android 开发者网站。 developer.android.com/guide/topics/resources/…

标签: java android arrays list csv


【解决方案1】:

不要尝试手动解析 CSV,因为这种格式有很多极端情况(引号转义等)。使用univocity-parsers,它应该可以正常工作。

试试这个代码:

    CsvParserSettings config = new CsvParserSettings();
    //configure what you need by hand, or just do this:
    config.detectFormatAutomatically();

    CsvRoutines csv = new CsvRoutines(config);

    File input = new File("C:\\Users\\MyName\\Documents\\MyApplication\\app\\src\\main\\res\\raw\\geo_locations.csv");

    Map<String, GeoLocation> locations = new LinkedHashMap<String, GeoLocation>();
    for(GeoLocation geo : csv.iterate(GeoLocation.class, input)){
        locations.put(geo.city, geo);
    }

我的GeoLocation 实现:

public class GeoLocation{
    @Parsed(index = 0)
    String city;
    @Parsed(index = 1)
    Double longitude;
    @Parsed(index = 2)
    Double latitude;
    @Parsed(index = 3)
    TimeZone timeZone;

    public void setTimeZone(String timeZone){
        this.timeZone = TimeZone.getTimeZone(timeZone);
    }
}

【讨论】:

    【解决方案2】:

    按照@Fildor 所说的那样更改文件路径,例如“assets”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2019-10-05
      • 2016-11-20
      相关资源
      最近更新 更多