java_IO
java_IO
COMP 180
IO
The simplest way to do IO: the scanner class
Very flexible and easy to use.
Can read from the console or from a file
The scanner class
Example
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
object
InputStream
OutputStream
FileInputStream
FileOutputStream
ByteArrayInputStream ByteArrayOutputStream
PipedInputStream
PipedOutputStream
ByteStreams: example
import java.io.*;
class CountBytes {
public static void main(String[] args)
throws IOException
{
InputStream in;
if (args.length == 0)
in = System.in;
else
in = new FileInputStream(args[0]);
int total = 0;
while (in.read() != -1)
total++;
System.out.println(total + “ bytes”);
}
}
Character Streams
Reader and Writer streams
Abstract classes
The parent class of all character streams
Defines the methods common to all character streams
These methods correspond to
InputStream/OutputStream methods
Example:
of an int as a byte
Read method of Reader returns lowest 16 bits of an
int as a char
Character Streams
Reader and Writer
object
Reader
Writer
InputStreamReader
OutputStreamWriter
CharArrayReader CharArrayWriter
BufferedReader
BufferedWriter
Character Streams: Example
import java.io.*;
class CountSpace {
public static void main(String[] args)
throws IOException
{
Reader in;
if (args.length == 0)
in = new InputStreamReader(System.in);
else
in = new FileReader(args[0]);
int ch;
int total;
int spaces = 0;
for (total = 0; (ch = in.read()) != -1; total++) {
if (Character.isWhitespace((char) ch))
spaces++;
}
System.out.println(total + “ chars, “ + spaces + “ spaces”);
}
}
Example: Console I/O
To read from the console (System.in) you need to be able to
read characters.
You can change the byte stream to a character stream
In this case, the token is the entire line – the linefeed character
is used to determine when to stop putting characters into the
buffer.
StreamTokenizer tokenizer;
tokenizer = new StreamTokenizer(fileIO);
Next use the streamTokenizer method nextToken( )to get the next
token from the stream
Returns the token type not the actual value
nextToken = tokenizer.nextToken();
try {
nextToken = tokenizer.nextToken(); //get the first token
while (nextToken != StreamTokenizer.TT_EOF) {
// … more code here
} //while
}//try
catch (IOException err) {
// this code executes if there is an error in getting the next token
System.out.println(err);
}//catch
Tokenizers
Tokenizer returns the type of the token.
Tokenizer classes provide flags (as static properties)
Class constants that are set when the token is retrieved
Provide information about the token
Examples:
TT_EOF
TT_EOL
TT_WORD
TT_NUMBER
These last two allow you to determine the data type of the
token before converting it if you don’t know what type you
are expecting – or to do error checking.
File IO example with tokens
// This is from the previous example