Java 學習記錄84 — I/O BufferedReader — 3/7

張小雄
Oct 14, 2021

--

承 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();
}
}

第三種寫法

這個寫法就簡單多了

因為我們文檔規律很簡單

這樣寫就不像上面兩種方法那樣麻煩跟難寫

補充:

Scanner vs. BufferedReader

3 ways for reading user’s input from console in Java

本篇代碼

--

--

張小雄
張小雄

Written by 張小雄

記錄成為軟體工程師的過程

No responses yet