1 / 22

IO Streams

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 {

lilia
Télécharger la présentation

IO Streams

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. IO Streams COMP 180

  2. 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

  3. 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

  4. 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

  5. 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)

  6. 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

  7. 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

  8. 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”); } }

  9. 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

  10. Character Streams • Reader and Writer object Reader Writer InputStreamReader OutputStreamWriter CharArrayWriter CharArrayReader BufferedReader BufferedWriter

  11. 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”); } }

  12. 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

  13. 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.

  14. 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.

  15. 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

  16. 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

  17. 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

  18. 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

  19. 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.

  20. 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 }

  21. // 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

  22. 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

More Related