(c) copyright 2001, 2002, 2003, 2004 by Daniel Berleant
Reading from files and URLs
Problem:
There are lots of I/O classes
Best solution:
You carefully pick the right one
Not-as-good solution:
Someone picks the first class that catches their attention
Characters vs. Bytes
Classes for reading are in java.io.*
Some reading classes have "...Reader.." in the name
FileReader - for reading text files
BufferedReader - for "buffered" reading of text
- has a readLine() method
InputStreamReader - reads bytes, outputs chars
Etc.
If it has "...Reader..." in the name -
. . . it relates to text (bunches of chars)
Some reading classes have "...Stream..." in the name
InputStreamReader - (this has "Stream" AND "Reader" in it)
FileInputStream - reads bytes from a file
BufferedInputStream - buffers, so fewer disk accesses
DataInputStream - reads bytes, converts to ints, etc.
- has read(), readInt(), readBoolean(), etc., methods
Etc.
If it has "...Stream..." in the name -
It relates to bytes
Reading: Fast and Slow
The Theory:
Disk accesses are slow
To go faster, read(write) lots per disk access
To go slower, read(write) one byte/char/etc. per disk access
Solution 1: YOU read lots per disk access
int amount;
InputStream f =
new
FileInputStream("proteinNames1.txt");
amount=f.available();
byte buffer[]=
new byte[amount];
if(f.read(buffer) != amount)
System.err.println
("Couldn't read "+ amount + " bytes");
To go even slower, use a loop & read one byte per loop
Computer does a special disk access for each byte
Solution 2: tell the JAVA system to read lots per disk access
BufferedReader - "buffers" a text file
BufferedInputStream - "buffers" a data (byte) file
Buffering means:
The computer reads files in largish chunks
... stores the chunks in memory
You can read one byte/char at a time
...but you are getting them from the buffer
When buffer runs dry, computer reads another chunk
It's automatic - you don't have to worry about it