1 / 40

File Streams for Input

File Streams for Input. Stream. Stream A sequence of data Standard I/O stream File stream. Standard input stream. Standard output stream. Keyboard. Your program. Display. File input stream. File output stream. Input File. Your Program. Output File. FileInputStream class.

arnie
Télécharger la présentation

File Streams for Input

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. File Streams for Input

  2. Stream Stream • A sequence of data • Standard I/O stream • File stream Standard input stream Standard output stream Keyboard Your program Display File input stream File output stream Input File Your Program Output File

  3. FileInputStream class To create an input stream connected to a file, create an instance of the FileInputStream class FileInputStream inputFile = new FileInputStream("/phw /onto/ java/ input.data") ; • "/phw/onto/java/input.data" : path and file specification • Given a file input stream, you can read one byte at a time • To read numbers or strings, convert a FileInputStream instance into a StreamTokenizer instance

  4. StreamTokenizer StreamTokenizer instance StreamTokenizer tokens = new StreamTokenizer( input File); • tokens : StreamTokenizer variable • inputFile : FileInputStream instance • Treat whitespace characters as delimiters that divide character sequences into tokens

  5. nextToken() Method nextToken() method move a tokenizer to the next token • token_variable.nextToken() nextToken() returns the token type as its value • StreamTokenizer.TT_EOF : end-of-file reached • StreamTokenizer.TT_NUMBER : a number was scanned;the value is saved in nval(double); if it is an integer, it needs to be typecasted into int ((int)tokens.nval) • StreamTokenizer.TT_WORD : a word was scanned; the value is saved in sval(String)

  6. java.io Package Input-output package • To work with file input stream, include - import java.io.FileInputStream • Alternatively ,include - import java.io.* When finished with an input file, close it • inputFile.close()

  7. IO Exception In event that a horrible input-output error occurs, Java throws an exception • A file does not exist • Try to read from an empty stream You must tell java what to do when exceptions are thrown • Use try-catch statements (Catch), or • Indicate a method contains statements that may throw exceptions (Specify)

  8. Specifying IO Exception public class Demonstrate { public static void main(Stringargv[]) throws IOException { … } } • throws : exception-indicating keyword • IOException : exception class Exceptions will be covered later in detail.

  9. An Example import java.io.*; public class Demonstrate { public static void main(String argv[]) throws IOException { FileInputStream inputFile = new FileInputStream("input.data"); StreamTokenizer tokens = new StreamTokenizer(inputFile); while((next = tokens.nextToken()) != tokens.TT.EOF) { int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x, y, z); System.out.println("Rating: " + m.rating()); } inputFile.close(); } }

  10. An Example (cont’) --------------------- Sample Data ------------------------------------- 4 7 3 8 8 7 2 10 5 ------------------------------------------------------------------------------ Rating: 14 Rating: 23 Rating: 17 -------------------------------------------------------------------------------

  11. Another Example Ignores strings in the input data import java.io.*; public class Demonstrate { public static void main(String argv[]) throws IOException { FileInputStream inputFile = new FileInputStream("input.data"); StreamTokenizer tokens = new StreamTokenizer(inputFile); int next = 0; while((next = tokens.nextToken()) != tokens.TT.EOF) { switch(next) { case tokens.TT.WORD: break; case tokens.TT.NUMBER: int x = (int) tokens.nval; tokens.nextToken();int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; Movie m = new Movie(x, y, z); System.out.println("Rating: " + m.rating());

  12. Another Example (cont’) break; } } inputFile.close(); } } --------------------- Sample Data --------------------------------------- The Sting 4 7 3 Titanic 8 8 7 My Way 2 10 5 --------------------------------------------------------------------------------

  13. Create and Access Arrays

  14. Array Array • An Array instance • Contains a collection of elements • Java stores and retrieves using an integer index • Zero-based arrays - First element is indexed by zero • Variables typed with arrays are said to be reference variables 0 1 2 3 <- Index --------------------------------- 65 87 72 75

  15. Array Variable Declare an array-type variable x int x[]; // or int[] x; (prefered) Array-type variables are also reference variables like class-type variables and requires the new operator int x[] = new int [4]; // creates an array of four integers Use of an array: x[2] = 46;

  16. One-dimentional Array Declare and initialize a one-dimentional array • data type array_name[] = new data type[number_of_elements]; - data_type array_name[] :declare - new data_type[number_of_elements] : create Combine array creation and element insertion • Using an array initializer - int[] x = {65,87, 72, 75 }; - int[] x = new int[] {65, 87, 72, 75};(JDK1.1)

  17. Dynamic Allocation Java array can be allocated dynamically • the array size can be determined at run-time public static int[] creat.int.array(int size) { int[] x = new int [size]; return x; }

  18. Dynamic Allocation (cont’) • Once a Java array is created, it is allocated in heap and its size is fixed for its lifetime. • Must distinguish array variable and array object : Java array is an object • Note it is the length of the array object that is fixed, not the array variable public static void main(String argv[]) { int[] x = new int [10]; .… x = new int [100]; } public static void main(String argv[]) { int[] x = {1,2,3,4}; int[] y = {5,6,7,8,9}; x = y; }

  19. Accessing Array Write a value into the array at a specified position • array_name[index] = expression; Whether an array has been assigned a value at a specified position • array_name[index] == null Read a value stored in an array at a specified position • array_name[index] The length of an array • array_name.length

  20. Example public class Demonstrate { public static void main(String argv[]) { int counter,sum = 0; int durations[] = { 65, 87, 72, 75}; for(counter = 0; counter < duration.length; ++counter) sum = sum + duration[counter]; System.out.print("The average of the " + duration.length); System.out.println(" durations is " + sum / durations.length); } }

  21. Array of Class Instances Declare and initiallize a Movie array variable • Movie movies[] = new Movie[4]; Insert a Movie instance into an array • movies[counter] = new Movie(); Alter the instance variables in that Movie instance • movies[counter].script = 6; Read data from the movies array • movies[counter].script

  22. Array of Class Instances(cont’) Initial value of elements in the array is null • To check if array instances at particular place is written - movies[counter] == null Use an array element as an instance method target • movies[counter].rating() Combine array creation and element insertion • Movie movies[] = {new Movie(5, 6, 3), new Movie(8, 7, 7), new Movie(7, 2, 2), new Movie(7, 5, 5)};

  23. Example The value of an element of an array declared for a particular class can be an instance of any sub class of that class (polymorphism) public class Demonstrate { public static void main(String argv[]) { int counter, sum = 0; Attraction attractions[] = { new Movie(4, 7, 3), new Movie(8, 8, 7), new Symphony(10, 9, 3), new Symphony(9, 5, 8)}; for(counter = 0; counter < attractions.length; ++counter) { sum = sum + attractions[counter].rating(); } System.out.print("the average rating of the " + attractions.length); System.out.println(" attractions is " + sum / attractions.length); } }

  24. How array objects are implemented • Contains a length instance variable • Primitive types (int array, float array, etc) • Consecutive bytes of memory occupied by each element Memory for length instance variable Memory for four int instances Array Object Implementation

  25. Reference types: cannot store elements consecutively ( why not? Consider an array of Attraction class ) • Several bytes of memory for the address of every instances Memory for length instance variable Memory for four addresses Instance Instance Instance Instance Array Object Implementation ( cont. )

  26. Arrays are implicit extensions of Object and you can invoke any Object method on them public static void main(String argv[]) { int[] x = -1,2,3,4""; int[] y = -5,6,7,8,9""; x = (int[]) y.clone(); } Object int [] float [] X X [] Y Y [] Array Object Implementation ( cont. )

  27. Array Object Implementation ( cont. ) • Array name is a variable, not a constant as in C • Like any other objects, array objects are garbage collected • Polymorphism is allowed for arrays • Cannot extend array type ( class x extends int[] )

  28. n Dimensional Array Define array with more than one dimension • Add more bracketed dimension sizes double 2DArray[][] = new double[2][100];

  29. Array Parameters and Return Values How to move arrays into and out of methods Read in movie-rating information from a file, create movie instances, and store into an array

  30. Example public class Demonstrate { public static Movie[] readData(Movie movies[]) throws IOException { FileInputStream inputFile = new FileInputStream("input.data"); StreamTokenizer tokens = new StreamTokenizer(inputFile); int movieCounter = 0; Movie movies[] = new Movie[100]; while(tokens.nextToken() != tokens.TT.EOF) { int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; movies[movieCounter] = new Movie(x, y, z); ++movieCounter; } inputFile.close(); } }

  31. Package the file-reading and array-writing program into a method Pass an array as a parameter, and returns an array Equivalently Returned value is a movie array Parameter type is a movie array Parameter name public static Movie[] readData ( Movie [] movies ) throws IOException { … } Optional space public static Movie[] readData ( Movie movies [] ) throws IOException { … } Array Parameter and Return

  32. Example Demonstrate.java import java.io.*; public class Demonstrate { public static void main(String argv[]) throws IOException { Movie mainArray[] = new Movie[100]; mainArray = Auxiliaries.readData(mainArray); int counter; Movie m; for(counter= 0; (m = mainArray[counter]) != null; ++counter) { System.out.println(m.rating()); } } }

  33. Example ( cont. ) Auxiliaries.java import java.io.*; public class Auxiliaries { public static Movie[] readData(Movie movies[]) throws IOException { FileInputStream inputFile = new FileInputStream("input.data"); StreamTokenizer tokens = new StreamTokenizer(inputFile); int movieCounter = 0; while(tokens.nextToken() != tokens.TT.EOF) { int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; movies[movieCounter] = new Movie(x, y, z); ++movieCounter; } inputFile.close(); return movies; } }

  34. Array Argument When you hand an array argument to a method • The array address is copied • Assigned to the corresponding method parameter • The array itself is not copied import java.io.*; public class Demonstrate { public static void main(String argv[]) throws IOException { Movie mainArray[] = new Movie[100]; Auxiliaries.readData(mainArray); … } }

  35. import java.io.*; public class Auxiliaries { public static void readData(Movie movies[]) throws IOException { FileInputStream inputFile = new FileInputStream("input.data"); StreamTokenizer tokens = new StreamTokenizer(inputFile); int movieCounter = 0; … inputFile.close(); } } mainArray, in main movies, in readData Address Addresscopy Chunk of memory representing the array Array Argument ( cont. )

  36. Three Ways for main-readData Combination • Create an array in main, hand over the address to readData, on return the address is handed back • Create an array in main, hand over the address to readData, nothing is returned • Only declare an array variable in main, create the array in readData ,hand it back as the value of readData import java.io.*; public class Demonstrate { public static void main(String argv[]) throws IOException { Movie mainArray[] = Auxiliaries.readData("input.data"); … } }

  37. Three Ways for main-readData Combination ( cont. ) import java.io.*; public class Auxiliaries { public static Movie[] readData(String fileName) throws IOException { FileInputStream inputFile = new FileInputStream(fileName); StreamTokenizer tokens = new StreamTokenizer(inputFile); Movie movies[] = new Movie[100]; int movieCounter = 0; … inputFile.close(); return movies; } }

  38. main method parameter The main method has just one parameter, argv • Assigned to an array of String instances • Length of the array is equal to the number of command-line arguments provided • Each element corresponds to one command-line argument public class Demonstrate { public static void main(String argv[]) { int counter; int max = argv.length; for(counter = 0; counter < max; ++counter) { System.out.println(argv[counter]); } } }

  39. main method parameter ( cont. ) Run the program as follows java Demonstrate This is a test This is a test

  40. String Convert Convert strings to integers using parseInt class method of the Integer class public class Demonstrate { public static void main(String argv[]) { Movie m = new Movie(Integer.parseInt(argv[0]), Integer.parseInt(argv[1]), Integer.parseInt(argv[2])); System.out.println("The rating is " + m.rating()); } } Run the program as follows java Demonstrate 4 7 3 The rating is 14

More Related