230 likes | 341 Views
IO Streams. 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; public class scanIn {
E N D
IO Streams 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; public class scanIn { public static void main(String[] args) { String first, last; int ssn; try{ Scanner sc = new Scanner(new File("input.txt")); while (sc.hasNext()) { first = sc.next(); last = sc.next(); ssn = sc.nextInt(); System.out.println("First: " + first + "\nLast: " + last + "\nSSN: " + ssn); } }catch (FileNotFoundException e){ System.out.println(e); } //end catch } //end main } // end class
Streams • A stream is a ordered sequence of bytes that can be used as • A source for input (input stream) • A destination for output (output stream) • A program can have multiple streams • Examples: console, files, sockets, memory, strings • The java classes in the package java.io provide utilities for dealing with streams
Streams • Java categorizes streams in multiple ways: • input or output • character (16-bit unicode characters) or byte (8 bits) • data or processing (manipulates the stream data)
Streams • To read data, a JAVA program opens a stream on a source (such as a file, memory, or a socket) It then reads the information sequentially • To send information to an external destination, the program opens a stream to the destination and writes the data sequentially to the stream • Java has predefined byte streams: • System.in • System.out • System.err
Byte Streams • InputStream and OutputStream • Abstract classes • The parent class of all byte streams • Defines the methods common to all byte streams object InputStream OutputStream FileInputStream FileOutputStream ByteArrayOutputStream ByteArrayInputStream 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: • Read method of InputStream returns lowest 8 bits 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 CharArrayWriter CharArrayReader 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 • InputStreamReader charReader = new InputStreamReader(System.in); • This will read each individual character. To get tokens*, turn the input stream into a BufferedReader object: • BufferedReader consoleReader = new BufferedReader(charReader); * a token is a set of characters surrounded by white space
Example: Console I/O • Now use the readLine() method of BufferedReader to read a line from the console (a string): String input = consoleReader.readLine(); • In this case, the token is the entire line – the linefeed character is used to determine when to stop putting characters into the buffer. • To change a String into a number: int count = Integer.parseInt(input); // there is also a Double • Note: System.out is predefined to print numbers and strings.
File IO example // you must have these import statements at the top of the file: import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileNotFoundException; BufferedReader fileIO = null; StreamTokenizer tokenizer; File inputFile = new File("pay.txt"); //the input file //create a buffered stream to read from the file try { FileReader fileStream = new FileReader(inputFile); // or just: FileReader fileStream = new FileReader(“pay.txt”); BufferedReader fileIO = new BufferedReader(fileStream); } catch(FileNotFoundException err) { System.out.println(err); System.exit(-1); // exit if file not found } 1. You must create a file object to represent the file. 2. You can then turn the File object into a FileReader. FileReader turns bytes into unicode characters 3. A BufferedReader will let you read in lines of characters. Opening a file throws a FileNotFoundException. You must catch it! The rest of this example is given in a later slide.
Tokenizer • One often wants to read entire words or numbers from a stream • Without having to put one datum per line • Using a delimiter other than new line • To assist in reading meaningful aggregates of data from a stream, JAVA provides Tokenizers • StreamTokenizer class reads tokens from a stream • StringTokenizer extracts tokens from a String that has been read into memory
Creating a tokenizer on a file stream • Create a tokenizer on the file’s BufferedReader • While there is still data • Get the next token • Translate the token into the appropriate data type • Use the data • continue
Tokenizers • How streamTokenizer works: • First create a new token stream: 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(); • Now you can get the value of the token using String name = tokenizer.sval; // sval is value of the next token as a string double hours = tokenizer.nval; // nval is the value of the next token as a number
Tokenizers • Note: you must catch the IOException when getting tokens: 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 BufferedReader fileIO = null; StreamTokenizer tokenizer; File inputFile = new File("pay.txt"); //the input file //create a buffered stream to read from the file try { FileReader fileStream = new FileReader(inputFile); fileIO = new BufferedReader(fileStream); } catch(FileNotFoundException err) { System.out.println(err); System.exit(-1); // exit if file not found }
// now we tokenize that stream int nextToken; double hours, rate; String name; tokenizer = new StreamTokenizer(fileIO); try { //this will cause the stream to get the next token. It does NOT return //the actual token, but returns a code that indicates what type was read nextToken = tokenizer.nextToken(); //get the first token //we know the data types we are reading while (nextToken != StreamTokenizer.TT_EOF) { name = tokenizer.sval; //name is a string nextToken = tokenizer.nextToken(); hours = tokenizer.nval; //hours is a number nextToken = tokenizer.nextToken(); rate = tokenizer.nval; //rate is a number //get the next token nextToken = tokenizer.nextToken(); } //while }//try catch (IOException err) { // this code executes if there is an error in getting the next token from the file System.out.println(err); }//catch
Console IO example with tokens // example of tokenizing the console (from fileIOmain.java) BufferedInputStream consoleIO = new BufferedInputStream(System.in); //now create a tokenizer on the buffered stream to read tokens StreamTokenizer tokenizer = new StreamTokenizer(consoleIO); tokenizer.eolIsSignificant(true); // tell tokenizer to recognize end-of-line System.out.println("Enter a line of input: "); while(!done ) {// get each successive token until an oel is seen try { nextToken = tokenizer.nextToken(); //get the token if (nextToken == StreamTokenizer.TT_EOL) // is it an eol? done = true; else if (nextToken == StreamTokenizer.TT_WORD) { //is it a word stringToken = tokenizer.sval; //convert to string System.out.println("the token is " + stringToken); } else if (nextToken == StreamTokenizer.TT_NUMBER) { //is it a number numberToken = tokenizer.nval; //convert to double System.out.println("the token is " + numberToken); } } //try create tokenizer catch (IOException err) { System.out.println("IOException reading from consoleIO"); } //catch } //while