将 CSV 坐标文件拆分为经度和纬度 ArrayLists

问题描述 投票:0回答:1

我有一个包含一堆坐标的 CSV 文件。在文件中,坐标对用逗号分隔。我已经将这些对分开并将它们放入字符串的 ArrayList 中。现在, 我试图将每一对分成各自的经度和纬度 ArrayList。所以本质上,我试图使用 .split() 函数两次(将坐标分成对,将这些对分成经度和纬度值),并且我正在努力弄清楚如何第二次使用 split 。我不确定我到底做错了什么,或者完成此操作的正确语法是什么。我正在使用Java工作。这是我尝试过的:

Path countyCoords = Paths.get("countyCoords.txt");
File coordsData = countyCoords.toFile();
    
FileReader frCoords = null;
BufferedReader brCoords = null;
    
ArrayList<String> coordsList1 = new ArrayList<>();
    
ArrayList<String> longitude = new ArrayList<>();
ArrayList<String> latitude =  new ArrayList<>();
    
try {
    frCoords = new FileReader(coordsData);
    brCoords = new BufferedReader(frCoords);
        
    String lineReader = brCoords.readLine();
    
    while (lineReader != null) {
        System.out.println("Coords: "+lineReader);
        String[] threeLine = lineReader.split(",");
        String[] values = threeLine.split(" ");
        coordsList1.add(threeLine);
        String lon = values[0];
        String lat = values[1];
            
        longitude.add(lon);
        latitude.add(lat);
            
        lineReader = brCoords.readLine();
    }
} catch (IOException ex) {
    System.err.println("Error: "+ex.getMessage());
} finally {
    try {
        if (brCoords != null) {
            brCoords.close();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        System.exit(0);
    }
}
arraylist split coordinates latitude-longitude
1个回答
0
投票

假设您的数据格式为

1 2, 3 4, 5 6

以下代码片段可用于处理数据文件中的一行。我省略了异常处理、资源关闭。

String line = brCoords.readLine();
String[] coords = line.split(",");
for(String c : coords) {
  String[] lonLat = c.split(" ");
  longitude.add(lonLat[0]);
  latitude.add(lonLat[1]);
}
© www.soinside.com 2019 - 2024. All rights reserved.