[英]store from list string to another array list
我有一個這樣的txt文件,其中包含經度和緯度坐標:
120.12 22.233
100 23.12
98 19.12
如果我想讀取文件,我在做:
List<String> lines = Files.readAllLines(Paths.get(fileName));
System.out.println("LINE: " + lines.get(0));
它給了我: 120 22
我有一堂課讀緯度和經度:
public class GisPoints {
private double lat;
private double lon;
public GisPoints() {
}
public GisPoints(double lat, double lon) {
super();
this.lat = lat;
this.lon = lon;
}
//Getters and Setters
}
我想將txt文件中的所有值存儲到List<GisPoints>
。
所以,我想要一個函數來加載文件:
public static List<GisPoints> loadData(String fileName) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(fileName));
List<GisPoints> points = new ArrayList<GisPoints>();
//for (int i = 0; i < lines.size(); i++) {
// }
return points;
}
就像我說的,現在我正在讀取每一行,例如lines[0] = 120 22
我想將經線[0]存儲到points [0] .setLon()中,將經線[0]緯度存儲到points [0] .setLat()中。
這是使用String.split()的簡單解決方案
private GisPoints createGisPointsObjectFromLine(String p_line)
{
String[] split = p_line.trim().split(" ");
double lat = Double.parseDouble(split[0]);
double lon = Double.parseDouble(split[split.length - 1]);
return GisPoints(lat, lon);
}
您可以從loadData()方法調用此方法。 我希望此解決方案有幫助。 祝好運!
for (String str : lines) {
String[] helpArray = str.split("\\s+"); // or whatever is betweeen
// the two numbers
points.add(new GisPoints(Double.valueOf(helpArray[0].trim()), Double.valueOf(helpArray[1].trim())));
}
這應該在您需要時起作用。 僅在文件中只有數字的情況下才有效。 如果您需要進一步的幫助,可以報告
我想將經線[0]存儲到points [0] .setLon()中,將經線[0]緯度存儲到points [0] .setLat()中。
您不需要馬上設置。 您已經有一個很好的構造函數來接收它們兩者。
將對象分成兩部分后,只需創建一個對象即可。
for (int i = 0; i < lines.size(); i++) {
String[] latlang = lines.get(i).split("\\s+");
GisPoints g = new GisPoints(Double.parseDouble(latlang[0].trim()),Double.parseDouble(latlang[1].trim()));
points.add(g)
}
我認為split
可以解決您的問題:
String arr[] = lines[i].split("\\s+");
GisPoints p = new GisPoints(Double.parseDouble(arr[0]), Double.parseDouble(arr[1]));
您可能要使用java8-streams做到這一點:
List<GisPoint> points = lines.stream()
.map(s -> s.split("\\s+"))
.map(array -> Arrays.stream(array)
.map(String::trim)
.filter(s -> !s.isEmpty())
.mapToDouble(Double::parseDouble)
.toArray()
)
.map(array -> new GisPoint(array[0], array[1]))
.collect(Collectors.toList());
它看起來像這樣:
for (int i = 0; i < lines.size(); i++)
{
String line = lines.get(i);
String[] values = line.split("\\s+");
double lat = Double.parseDouble(values[0]);
double lon = Double.parseDouble(values[1]);
points.add(new GisPoints(lat, lon));
}
看看班級Scanner; 掃描儀有很多有用的工具來讀取和解析字符串。
用正則表達式看一下:
import java.util.regex.*;
public class HelloWorld{
public static void main(String []args){
String line = "98 19";
Pattern pattern = Pattern.compile("^(\\d+)\\s*(\\d+)$");
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
System.out.println("group 1: " + matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.