file streams for input

40
File Streams for Input File Streams for Input

Upload: arnie

Post on 14-Jan-2016

49 views

Category:

Documents


0 download

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 Presentation

TRANSCRIPT

Page 1: File Streams for Input

File Streams for InputFile Streams for Input

Page 2: File 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

Page 3: File Streams for Input

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

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

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

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

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

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

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

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

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

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

Create and Access ArraysCreate and Access Arrays

Page 14: File Streams for Input

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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