The sometimes confusing world of Java I/O
Java supports many kinds of I/O Streams.
Specialized by the type of data processed
- Byte streams read and write 8-bit bytes
- Character streams read and write Unicode characters
- Data streams read and write primitive values and
String
objects - Object streams read and write
Serializable
objects
Specialized by how the data is processed
- Methods of the Scanner classes break input into tokens.
- Every serious web programmer needs to known how regular expressions, as implemented in Java’s Pattern class, can be used to tokenize input.
- Using format strings, output can be neatly written.
PrintWriter
provides formatting for character output.PrintStreams
provides formatting for byte output.
What do we really have to know?
System.out
is aPrintStream
.- While
System.in
is only aInputStream
,new Scanner(System.in)
will create aScaner
for the “standard” input streams. new Scanner(new File("input.txt"))
will open an input file and return aScanner
.new PrintWriter(new File("output.txt"))
will open an output file and return aPrintWriter
.
Java 1.7 and beyond
Starting with version 1.7, Java has a new package
java.nio.file
for handling file access.
This package is much more sophiscated the the present java.io.file
class. This new package is not used in the textbook, and we will
not use it in class.
As far as I can I tell, you can use the following statement to open
a file as a Scanner
using the classes of the
java.nio.file
package.
new Scanner(FileSystems.getDefault().getPath("inFile.txt").toFile()) ;