File Streams for InputFile Streams for Input
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
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
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
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)
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()
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)
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.
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();}
}
An Example (cont’)An Example (cont’)
--------------------- Sample Data -------------------------------------
4 7 3
8 8 7
2 10 5
------------------------------------------------------------------------------
Rating: 14
Rating: 23
Rating: 17
-------------------------------------------------------------------------------
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());
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
--------------------------------------------------------------------------------
Create and Access ArraysCreate and Access Arrays
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
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;
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)
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;
}
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;
}
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
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);
}
}
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
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)};
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);}
}
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
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
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 []
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[] )
n Dimensional Arrayn Dimensional Array
Define array with more than one dimension
Add more bracketed dimension sizes
double 2DArray[][] = new double[2][100];
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
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();
}}
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
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());}
}}
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;
}}
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);…
}}
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
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");…
}}
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;
}}
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]);}
}}
main method parameter ( cont. )main method parameter ( cont. )
Run the program as follows
java Demonstrate This is a test
This
is
a
test
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
Top Related