承 83 — FileReader and Closeable
Locations.java
// read directions.txt - version3
try {
scanner = new Scanner(new BufferedReader(new FileReader("src/introduceIo/directions.txt")));
scanner.useDelimiter(",");
while (scanner.hasNextLine()) {
String input = scanner.nextLine();
String[] data = input.split(",");
int loc = Integer.parseInt(data[0]);
String direction = data[1];
int destination = Integer.parseInt(data[2]);
Location location = locations.get(loc);
location.addExit(direction, destination);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}
}
第三種寫法
這個寫法就簡單多了
因為我們文檔規律很簡單
這樣寫就不像上面兩種方法那樣麻煩跟難寫
補充:
3 ways for reading user’s input from console in Java