Files, Exceptions, and Abstractions: Lecture #7
Douglas Blank, Bryn Mawr College, CS206, Spring 2013
Similarities between Array and HashMap
Very similar in the abstract: they both have constant-time in setting and getting values
Differences between Array and HashMap
When something bad happens
Exceptions: rule of thumb
Otherwise, you might be calling lower level code, and it just "eats" the problem without any indication that something is wrong.
Catch and Throw
void someMethod() {
whereSomethingBadCanHappen();
}
Catch and Throw
void someMethod() throws Exception {
whereSomethingBadCanHappen();
}
Catch and Throw
void someMethod() {
try {
whereSomethingBadCanHappen();
} catch (Exception e) {
// recover
}
}
Input from a File
import java.io.*;
public class TestIO {
public static int countLines(File f) {
}�public static void main(String[ ] args) {
}
}
Input from a File
Would like to read a line from a text file
How to find the right Java class?
Input from a File: BufferedReader
Input from a File
BufferedReader br = new BufferedReader(� new InputStreamReader(� new FileInputStream(� new File("test.txt"))));
br.readLine() // returns null when done
br.close()
Input from a File: throw
public static int countLines(File f) throws IOException {� BufferedReader br = new BufferedReader(� new InputStreamReader(� new FileInputStream(f)));
int count = 0;� String line = br.readLine();� while (line != null) {� count++;
line = br.readLine();� }� br.close();� return count;� } �
Input from a File: throw
import java.io.*;
public class TestIO {
...
public static void main(String[ ] args) throws IOException {
System.out.println(countLines(new File("Fileio.java")));
}
}
Input from a File: catch
public static int countLines(File f) {
int count = 0;� try {� BufferedReader br = new BufferedReader(� new InputStreamReader(� new FileInputStream(f)));
String line = br.readLine();� while (line != null) {� count++;
line = br.readLine();� }� br.close();
} catch (IOException e) {
}� return count;� } �
Input from a File: catch
import java.io.*;
public class TestIO {
...
public static void main(String[ ] args) {
System.out.println(countLines(new File("Fileio.java")));
}
}
Interactive Game
String line = br.readLine();
while (line != null) {
...
line = br.readLine();
}
Game File
state: Field
descr: You are in a beautiful field.
command: north
to: Dungeon
state: Dungeon
descr: You are in the danky dungeon. � You smell onions.
command: south
to: Field
Interactive Game
String line = br.readLine();
while (line != null) {
if (line.StartsWith("state:")) {
} else if (line.StartsWith("descr:")) {
}
line = br.readLine();
}
Interactive Game
Let's write some code...