簡體   English   中英

在android中讀取CSV文件並將其放入Hashmap中

[英]Reading CSV file in android and putting it into a Hashmap

我正在嘗試將CS​​V文件中的數據添加到列表中。 目前我在下面有這個代碼,但只要我嘗試運行它,應用程序就會關閉。

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文件中獲取該列表,並從中創建一個我可以添加到“位置”的列表。

不要嘗試手動解析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);
    }
}

改變你的文件路徑@Fildor說,例如“資產”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM