|
|
|
Sponsored Link •
|
|
Advertisement
|
This is in deciding your contract. You shouldn't promise to do something unless the chances are you'll be able to do it most of the time.
FileInputStreamFileInputStream returns -1 on end of file.
read() again after hitting EOF, you'll
still get -1.
read() method
1 // In file ex9/Example9a.java
2 import java.io.*;
3 class Example9a {
4
5 public static void main(String[] args)
6 throws IOException {
7
8 if (args.length == 0) {
9 System.out.println("Must give filename as first arg.");
10 return;
11 }
12
13 FileInputStream in;
14 try {
15 in = new FileInputStream(args[0]);
16 }
17 catch (FileNotFoundException e) {
18 System.out.println("Can't find file: " + args[0]);
19 return;
20 }
21
22 int ch;
23 while ((ch = in.read()) != -1) {
24 System.out.print((char) ch);
25 }
26 System.out.println();
27
28 in.close();
29 }
30
StringTokenizer and StackStringTokenizer makes you ask hasMoreTokens() before
calling nextToken()
nextToken() after hasMoreTokens()
returns (or would return) false, you get an (unchecked)
NoSuchElementException
nextToken() method, because you are supposed to
check with hasTokens() first
1 // In file ex9/Example9c.java
2 // This program prints the white-space separated tokens of an
3 // ASCII file in reverse order of their appearance in the file.
4 import java.io.*;
5 import java.util.*;
6 class Example9c {
7
8 public static void main(String[] args)
9 throws IOException {
10
11 if (args.length == 0) {
12 System.out.println("Must give filename as first arg.");
13 return;
14 }
15
16 FileInputStream in = null;
17 try {
18 in = new FileInputStream(args[0]);
19 }
20 catch (FileNotFoundException e) {
21 System.out.println("Can't find file: " + args[0]);
22 return;
23 }
24
25 // Read file into a StringBuffer
26 StringBuffer buf = new StringBuffer();
27 try {
28 int ch;
29 while ((ch = in.read()) != -1) {
30 buf.append((char) ch);
31 }
32 }
33 finally {
34 in.close();
35 }
36
37 // Separate StringBuffer into tokens and
38 // push each token into a Stack
39 StringTokenizer tok = new StringTokenizer(buf.toString());
40 Stack stack = new Stack();
41 while (tok.hasMoreTokens()) {
42 stack.push(tok.nextToken());
43 }
44
45 // Print out tokens in reverse order.
46 while (!stack.empty()) {
47 System.out.println((String) stack.pop());
48 }
49 }
50
Stack makes you ask empty() before
calling pop()
pop() after empty()
returns (or would return) true, you get an (unchecked)
EmptyStackException
pop() method, because you are supposed to
check with empty() first
|
Sponsored Links
|