file streams for input
DESCRIPTION
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. - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/1.jpg)
File Streams for InputFile Streams for Input
![Page 2: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/2.jpg)
StreamStream
Stream A sequence of data Standard I/O stream
File stream
KeyboardYour program
Standard input stream
Standard output stream
Display
Input File Your Program
File input stream File output stream
Output File
![Page 3: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/3.jpg)
FileInputStream FileInputStream classclass
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 S
treamTokenizer instance
![Page 4: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/4.jpg)
StreamTokenizerStreamTokenizer
StreamTokenizer instance
StreamTokenizer tokens
= new StreamTokenizer( input File);
tokens : StreamTokenizer variable inputFile : FileInputStream instance Treat whitespace characters as delimiters that divide character sequenc
es into tokens
![Page 5: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/5.jpg)
nextToken() nextToken() MethodMethod
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 s
aved 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)
![Page 6: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/6.jpg)
java.io java.io PackagePackage
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()
![Page 7: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/7.jpg)
IO ExceptionIO 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)
![Page 8: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/8.jpg)
Specifying IO ExceptionSpecifying 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.
![Page 9: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/9.jpg)
An ExampleAn 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();}
}
![Page 10: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/10.jpg)
An Example (cont’)An Example (cont’)
--------------------- Sample Data -------------------------------------
4 7 3
8 8 7
2 10 5
------------------------------------------------------------------------------
Rating: 14
Rating: 23
Rating: 17
-------------------------------------------------------------------------------
![Page 11: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/11.jpg)
Another ExampleAnother 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());
![Page 12: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/12.jpg)
Another Example (cont’)Another Example (cont’)
break;
}
}
inputFile.close();
}
}
--------------------- Sample Data ---------------------------------------
The Sting 4 7 3
Titanic 8 8 7
My Way 2 10 5
--------------------------------------------------------------------------------
![Page 13: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/13.jpg)
Create and Access ArraysCreate and Access Arrays
![Page 14: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/14.jpg)
ArrayArray
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
![Page 15: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/15.jpg)
Array VariableArray 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;
![Page 16: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/16.jpg)
One-dimentional ArrayOne-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)
![Page 17: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/17.jpg)
Dynamic Allocation 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;
}
![Page 18: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/18.jpg)
Dynamic Allocation (cont’)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;
}
![Page 19: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/19.jpg)
Accessing ArrayAccessing 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
![Page 20: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/20.jpg)
ExampleExample
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);
}
}
![Page 21: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/21.jpg)
Array of Class InstancesArray 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
![Page 22: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/22.jpg)
Array of Class Instances(cont’)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)};
![Page 23: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/23.jpg)
ExampleExample
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);}
}
![Page 24: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/24.jpg)
Array Object ImplementationArray Object Implementation
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 four int instances
Memory for length instance variable
![Page 25: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/25.jpg)
Array Object Implementation ( cont. )Array Object Implementation ( cont. )
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 four addresses
Memory for length instance variable
Instance Instance Instance Instance
![Page 26: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/26.jpg)
Array Object Implementation ( cont. )Array Object Implementation ( cont. )
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 []
![Page 27: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/27.jpg)
Array Object Implementation ( cont. )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[] )
![Page 28: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/28.jpg)
n Dimensional Arrayn Dimensional Array
Define array with more than one dimension
Add more bracketed dimension sizes
double 2DArray[][] = new double[2][100];
![Page 29: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/29.jpg)
Array Parameters and Return ValuesArray 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
![Page 30: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/30.jpg)
ExampleExample
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();
}}
![Page 31: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/31.jpg)
Array Parameter and ReturnArray Parameter and Return
Package the file-reading and array-writing program into a method
Pass an array as a parameter, and returns an array
Equivalently
public static Movie[] readData ( Movie movies [] ) throws IOException {
…
}
Optional space
public static Movie[] readData ( Movie [] movies ) throws IOException {
…
}
Parameter type is a movie array
Parameter name
Returned value is a movie array
![Page 32: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/32.jpg)
ExampleExample
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());}
}}
![Page 33: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/33.jpg)
Example ( cont. )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;
}}
![Page 34: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/34.jpg)
Array ArgumentArray 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);…
}}
![Page 35: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/35.jpg)
Array Argument ( cont. )Array Argument ( cont. )
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();
}}
Chunk of memory representing the array
Address Addresscopy
mainArray, in main movies, in readData
![Page 36: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/36.jpg)
Three Ways for main-readData CombinationThree 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");…
}}
![Page 37: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/37.jpg)
Three Ways for main-readData Combination ( cont. )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;
}}
![Page 38: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/38.jpg)
main method parametermain 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 pr
ovided 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]);}
}}
![Page 39: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/39.jpg)
main method parameter ( cont. )main method parameter ( cont. )
Run the program as follows
java Demonstrate This is a test
This
is
a
test
![Page 40: File Streams for Input](https://reader036.vdocuments.mx/reader036/viewer/2022062301/568147c0550346895db50301/html5/thumbnails/40.jpg)
String ConvertString 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