[英]Reading CSV file in android and putting it into a Hashmap
我正在嘗試將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文件中獲取該列表,並從中創建一個我可以添加到“位置”的列表。
不要嘗試手動解析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.