There is a current position in the file's character stream. The current position starts out at the first character in the file, and moves one character over as a result of a character read (or write) to the file; to read the 10th character you need to first read the first 9 characters (or you need to explicitly move the current position in the file to the 10th character).
There are special hidden chars (just like there are in the stdin input stream), '\n', '\t', etc. In a file there is another special hidden char, eof, marking the end of the file.
The easiest way to read input is to create a new Scanner object from a passed File or FileInputStream object. The easiest way to write is to create a new FileWriter object from a passed File. These are not your only options, but they are the easiest ones to use.
try { Scanner reader = new Scanner(new FileInputStream("infile.dat");Or you can pass in a file name as a command line argument:
% java MyClass infile.txt"infile.txt" is passed as args[0] to main:
public static void main(String[] args) throws IOException { // first check to see if the program was run with the command line argument if(args.length < 1) { System.out.println("Error, usage: java ClassName inputfile"); System.exit(1); } Scanner reader = new Scanner(new FileInputStream(args[0]));
The Scanner class is used to read in tokens from an input stream. A token is a sequence of characters of some form that correspond to valid values of certain Java types. For example:
hello There goodbye
-123 22 34
hello 1234 there how are 5678 you?
If the input file named "infile.dat" has the following format:
Hello There 1234 CSstudents goodbye 6556it has six tokens that we can read in using the following code:
while (filein.hasNext()) { // while there is another token to read String s = filein.next(); // reads in the String tokens "Hello" "CSstudents" String r = filein.next(); // reads in the String tokens "There" "goodbye" int x = filein.nextInt(); // reads in the int tokens 1234 6556 System.out.println(s + ", " + r + ", " + x); }Notice how the Scanner object skips over all white-space characters to the start of the next token. For example, after reading the nextInt value 1234, the current position in the file in at the '\n' char after the 4 in the int 1234. If we had next called nextLine() instead of next() to read in the next full line as a String, we would have returned an empty string since the '\n' character is part of a valid line token. Instead, we called next to read in the next valid String token "CSstudents" which skips over all leading white space (i.e. '\n') and returns the String "CSstudents".
Also, note that this same code sequence would work if the input file was in this crazy format:
Hello There 1234 CSstudents goodbye 6556
FileWriter f = new FileWriter(new File("outfile"));
int x = 6; f.write("Hello " + x + "\n") f.write(1234 + " goodbye\n")Will produce file contents that look like this:
Hello 6 1234 goodbye
f.close();