我有一个读取文件的方法,然后将值传递给一个名为point的构造函数。还有另一个名为Track的类,它是一个显示旅程的点集合。
读取文件的方法不是抛出没有发现异常的文件,我不确定为什么。我尝试过try-catch方法失败,并帮助获取异常,以便深入了解为什么不理解它。
public static void readFile(String filename)
throws FileNotFoundException {
int i = 0;
ArrayList<String> textFile = new ArrayList<>();
Scanner input = new Scanner(System.in);
File file = new File(input.nextLine());
input = new Scanner(filename);
while (input.hasNext()) {
String letter = input.next();
textFile.add(i, letter);
i++;
}
input.close();
for (int j = 1; j < textFile.size(); j++) {
ZonedDateTime times;
double longitude = 0;
double latitude;
double elevation;
String s = textFile.get(j);
String[] half = s.split(",", 4);
times = ZonedDateTime.parse(half[0]);
longitude = Double.parseDouble((half[1]));
latitude = Double.parseDouble((half[2]));
elevation = Double.parseDouble((half[3]));
Point point = new Point(times, longitude, latitude, elevation);
add(point);
}
您正在从字符串构造Scanner对象,这意味着它只扫描该字符串(文件名),将其更改为
input = new Scanner(file);
并且您将使用抛出FileNotFoundException的构造函数
从Java文档:
public Scanner(String source)
构造一个新的Scanner,它生成从指定字符串扫描的值。
参数:
source - 要扫描的字符串
此方法不接受文件名作为参数,也不会抛出FileNotFoundException。
尝试使用:
public Scanner(文件源)抛出FileNotFoundException
构造一个新的Scanner,它生成从指定文件扫描的值。使用底层平台的默认字符集将文件中的字节转换为字符。
参数:source - 要扫描的文件
抛出:FileNotFoundException - 如果找不到source