-
Notifications
You must be signed in to change notification settings - Fork 16
/
FileCharIterator.java
61 lines (55 loc) · 1.72 KB
/
FileCharIterator.java
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
57
58
59
60
61
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
/**
* Returns each character of an input file, one at a time, in binary string
* format
*
*/
public class FileCharIterator implements Iterator<String> {
protected FileInputStream input;
private String inputFileName;
private int nextChar;
public FileCharIterator(String inputFileName) {
try {
input = new FileInputStream(inputFileName);
nextChar = input.read();
this.inputFileName = inputFileName;
} catch (FileNotFoundException e) {
System.err.printf("No such file: %s\n", inputFileName);
System.exit(1);
} catch (IOException e) {
System.err.printf("IOException while reading from file %s\n",
inputFileName);
System.exit(1);
}
}
@Override
public boolean hasNext() {
return nextChar != -1;
}
@Override
public String next() {
if (this.nextChar == -1) {
return "";
} else {
Byte b = (byte) this.nextChar;
String toRtn = String.format("%8s",
Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
try {
this.nextChar = this.input.read();
} catch (IOException e) {
System.err.printf(
"IOException while reading in from file %s\n",
this.inputFileName);
}
return toRtn;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException(
"FileCharIterator does not delete from files.");
}
}