-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCharReader.java
More file actions
56 lines (48 loc) · 1.45 KB
/
CharReader.java
File metadata and controls
56 lines (48 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package alda.huffman;
import java.io.*;
class CharReader {
public static final char NULL = (char)0;
public static final char EOF = (char)-1; // End of file.
private FileInputStream stream = null;
private InputStreamReader reader = null;
private char current = NULL;
public CharReader(String fileName){
try {
stream = new FileInputStream(fileName);
reader = new InputStreamReader(stream);
}catch(FileNotFoundException fe){
System.err.println("FileNotFound: " + fe+". Please make sure it exist." );
System.exit(0);
}
}
public char current() {
return current;
}
public void moveNext(){
try {
if (reader == null) throw new IOException("No open file.");
if (current != EOF) current = (char) reader.read();
else {
close();
}
}
catch (IOException e) {
System.err.println("IOException: " + e+". Error when reading file." );
System.exit(0);
}
}
public String getCharacters(int amount){
StringBuilder str = new StringBuilder();
for(int i = 0; i<amount; i++){
moveNext();
str.append(current);
}
return str.toString();
}
public void close() throws IOException {
if (reader != null)
reader.close();
if (stream != null)
stream.close();
}
}