Input and Output
Streams
- In Java, I/O handled with streams.
- Think of a stream as a sequence of data flowing from one place
to another (useful to think of as a buffer of data going one way or the
other).
- An input stream flows from an input source (e.g. keyboard, file) into
a program, usually to be stored in variables
- An output stream flows from a program to an output destination (e.g.
screen, file, network socket)
- I/O libraries are in the package
java.io
- Many built-in stream classes in Java, for processing different types
of data. Two primary categories: byte streams and character
streams
-
InputStream is the base class for byte stream input
classes
-
OutputStream is the base class for byte stream output
classes
-
Reader is the base class for character stream input
classes
-
Writer is the base class for character stream output
classes
Reading and Writing with Files
-
File is a class used for checking properties of files.
- Basic File I/O classes.
- For the input streams, the primary method is called read.
There is a version that reads one byte (or char), and a version that reads
an array of bytes (or chars).
- For the output streams, the primary methods are called
write. For writing single bytes (or chars) and for arrays of
byte (or chars).
Example:
CopyFileUsingByteStream.java -- example from text, which uses the file
stream classes to copy one file to another
Buffered Streams
Examples
- Test1.java -- This program reads
an input file and writes an all-uppercase copy of it to an output
file. First argument is the input file, second argument is the
output file.
- Test2.java -- This program reads
an input file and counts the number of times a word appears. First
argument is the input file, second argument is the word to search
for.
- Test3.java -- This program uses
some classes from the java.util package in addition to a file
reader, and it lists all the words in the input file along with the number
of times each word appears. The one command-line argument is the
input file.
- Frost.txt -- here is a sample text
file you can use to test each of these programs