asdfghjklmnbvcxz
Then if the program is run
java ShortRead ZZ.txt
the output should be
zbvcxHere are several more examples
| QWEZrtyu | yuErt |
| asd | asd |
| asd fgh | hsdfg |
Next make a file -- you name it -- with your name as the contents.
1 import java.io.FileReader;
2 import java.io.IOException;
3
4 public class ReadOne {
5 public static void main(String[] args) {
6 try {
7 FileReader r = new FileReader("ham.txt");
8 while (r.ready()) {
9 int int_read = r.read();
10 char char_read = (char) int_read;
11 System.out.println(int_read + " " + char_read);
12 }
13 }
14 catch (IOException e) {
15 System.out.println("Problem: " + e);
16 }
17 }
18 }
(Line numbers are included for the discussion below, they are not part of the code)
The Java FileReader class does exactly what you might expect, it reads files; to get it stated as on line 7, we give it the name of the file to be read. Then, just prior to actually reading anything, we ask the file reader, on line 8, if there is anything to read. If there is something to read, on line 9 we actually read it. The read returns the ASCII value of the character (see below), so on line 10 we convert that number into an actual character so that on line 11 we can print both the actual character and its ASCII value.
Java requires that anything that might have problems of a particular form be between "try" and "catch". For example, line 7 might have a problem if the file being opened did not exist. Similarly, line 9 might have a problem if the file disappeared between opening and line 9. If one of these bad things happen, the program immediately goes down to the catch (line 14) and executes whatever code is in the catch block (line 15). You should almost always have a print statement within the catch block. Sometimes it makes sense to have other things as well. So, all of this code that does the actions you actually want is in a block between the try (line 6) and the catch (line 14). We will discuss "try" and "catch" in class. The easiest thing to do will be to follow the pattern in the ReadOne program. That is make "try {" the first thing in the main method and
catch (IOException e) {
System.out.println("Problem: " + e);
return;
}
the last.
int ii = 70;
boolean bb = ii=='A';
if perfectly legal. This simply asks if the ascii integer value of the character 'A' is equal to 70 (it is not 'A' has a value of 65).
Likewise, this is legal
char cc = 'e';
boolean bb = cc==120;
bb = 'f' == 120;
In both cases bb is set to false because the ASCII int values of 'e' and 'f' are 101 and 102.
Note that chars in Java are denoted by single quotes, unlike strings that are denoted by double quotes.
Finally print out the final contents of the array.