【问题标题】:Using setters/getters on a text file在文本文件上使用 setter/getter
【发布时间】:2014-02-21 10:53:18
【问题描述】:

我正在尝试从一个文本文件中创建一个坐标列表,并且我希望能够高效地使用它,因此我创建了一个具有 latitudelongitude 双变量的类,以及它们的 getter 和 setter 方法.

所以在另一个类中,我创建了前一个类的对象以使用 setter 方法。

CoordinatesParams params = new CoordinatesParams();

如何从文本文件中读取坐标列表并将它们设置为latitudelongitude变量?

对不起,如果这个问题对某些人来说非常基础

File Bus_Routes = new File("C:/Users/Daniel Dold/Desktop/Routes/Bus_Routes.txt");
Scanner scanner = new Scanner(Bus_Routes);

String line = scanner.nextLine();
String[] parsed = line.split("\\s");
String routeText = parsed[0];

String dir = "C:/Users/Daniel Dold/Desktop/Routes/";
File routeFile = new File(dir, routeText);
Scanner sc = new Scanner(routeFile);
while(sc.hasNextLine())
{
    String line2 = sc.nextLine();
    String[] s = line2.split("\t");
}

这是我目前在文件上打印结果的内容。

51.50177649 -0.05012445
51.50210374 -0.05050666
51.50253617 -0.0509908
51.50265346 -0.05072191
51.50274404 -0.05055025
51.50301702 -0.05011841

坐标文件只有两列,第一列是纬度,第二列是经度

【问题讨论】:

  • 这取决于你的坐标是如何写入文件的。你也不能用谷歌搜索如何读取文件?
  • 我刚刚添加了我到目前为止所做的阅读文件
  • 请显示文件的一小部分以了解坐标是如何存储在其中的。
  • 好的,你试过我的答案了吗?
  • 工作就像一个魅力,谢谢凯

标签: java getter-setter


【解决方案1】:

我不知道文件在里面的样子,但是你应该为你的CoordinatesParamas 创建一个列表,然后遍历你从文件中读取的数据,用CoordinatesParamas 对象填充列表并设置纬度和经度this 通过 setter 对象。

List<CoordinatesParamas> lCoordinates = new ArrayList<CoordinatesParamas>();

while(sc.hasNextLine()) {
     CoordinatesParamas temp = new CoordinatesParamas();
     String pair = sc.nextLine();
     String[] s = pair.split(" ");
     temp.setLatitude(s[0])
     temp.setLongitude(s[1])
     lCoordinates.add(temp ); 
}

我将string.split("\t") 更改为split(" "),因为看起来坐标之间没有制表符,只有一个空格。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2022-06-11
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多