G51PR1 - PowerPoint PPT Presentation

1 / 37
About This Presentation
Title:

G51PR1

Description:

G51PR1. Introduction to Programming I. 2000-2001. University ... Perhaps we should first remember that input and output can be ... green blue black white ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 38
Provided by: OPA6
Category:
Tags: g51pr1 | argv | blueblack

less

Transcript and Presenter's Notes

Title: G51PR1


1
G51PR1
  • Introduction to Programming I
  • 2000-2001
  • University of Nottingham
  • Unit 9 Files and input/output

2
Overview
  • Streams
  • Input and Output Streams
  • Readers and Writers
  • Basic Stream Classes
  • Basic Readers and Writers
  • Examples
  • StreamTokenizer StringTokenizer
  • Introduction to I/O
  • Introduction to java.io
  • Files and input/output
  • The basics of file access
  • Files in java
  • Command Line Arguments
  • The Echo Program
  • Examples
  • Writing to a File
  • Reading from a File
  • Simultaneous Access
  • General about Files
  • Updating
  • Small files
  • Large files

3
Introduction
  • Perhaps we should first remember that input and
    output can be diverted from and to files in
    operating systems such as UNIX or MS-DOS without
    any program changes, provided that we are talking
    about all of the input or all of the output. Thus
    we can write
  • prog32 lt data_file
  • to run the program "prog32" taking all of its
    input from the file "data_file." This is the
    basis of the way programs were tested for dynamic
    correctness in the "Ceilidh command (now know as
    CourseMaster) against various sets of test data.
    Conversely, we can write
  • prog32 gt output_file
  • to store all of the (standard) output in the
    named file. This is how your program output is
    saved when CourseMaster tests the program. The
    dynamic testing system then searches the saved
    output for the keywords or phrases which the
    teacher has specified.

4
Introduction
  • The error output (anything using the System.err
    class) would still come to the terminal, and
    would not be diverted to the file.
  • This simple approach for diverting program input
    or output will satisfy some simple situations
    where we wish to use files instead of the
    terminal for input or output. However, for most
    realistic applications, we will need to
    communicate with standard input and output (the
    user's terminal) as well as one or more files.
  • We will generally need to interact with a user
    (print a prompt such as "When does the person
    arrive at Nottingham station?" on the terminal,
    and read the reply from the terminal) as well as
    interacting with the files of data (reading from
    a file containing the actual train timetables,
    and perhaps writing to a file of seat
    reservations).

5
Introducing java.io
6
The basics of file access
  • The approach to file input/output in most modern
    shared computer systems involves the program
    (i.e. any process wishing to access a file) in
    the following sequence of activities.
  • (i) Open the file. The name of the file and the
    type of access required (e.g. read, write, both,
    append, seek, ...) has to be known to open a file
    successfully. When the program runs, the system
    checks that the type of access requested is
    permitted in UNIX this involves the ownership of
    the file, the access permissions for that file
    defined by its owner (perhaps modified using the
    "chmod" command, and defined in terms of "read"
    or "write" or "execute" for the "owner", their
    "group" and the "others"), the identity of the
    user running the program.

1.Open File
2.Access File
3.Close File
7
The basics of file access
  • (ii) Access the file.
  • The program will not be allowed to read the file
    if it has asked only for "write"
    permission.
  • The program now refers to the file not by name,
    but by a variable used when constructing
    a stream of some kind.
  • Information is now read from the file, or
    written to it.
  • There is usually no consideration of the fact
    that the permissions on the file could be changed
    after the open has taken place once the file has
    been successfully opened, access is permitted
    until the file is closed or the process
    terminates.
  • (iii) Close the File.
  • This is often built into the program termination
    activity, so that the user does not need to take
    any closing action.
  • There may be upper limits on the number of files
    simultaneously open on certain systems, so this
    may necessitate closing files as soon as access
    to them is no longer required.

8
Files in Java
  • Files are made under UNIX and Windows to appear
    very similar to any other form of serial
    input/output device.
  • Thus in the ordinary command shell, output can be
    directed to the terminal, or to a file, or to
    another process, with no fundamental change to
    the process producing the output.
  • The operating system is hiding from the user what
    are in reality great differences between the
    physical processes of sending characters to a
    terminal and sending them to file.

9
Files in Java
file
network
windows
file
screen
network
unix
A message
Stream
file
screen
  • Java takes this one step further and hides even
    the operating system etc from you, so that you
    manipulate files as streams in a device/operating
    system independent way.

network
Mac/os
screen
10
Command-line arguments
  • The single argument to main() is an array of
    Strings, conventionally names args or argv.
  • The length of the array is available as
    argv.length.
  • The elements of the array are the arguments (if
    any) that appear on the interpreter command line
    after the class name.
  • C\java Echo red green blue black white
  • (For C programmers, note that the zeroth element
    is NOT the name of the class as might be
    expected.
  • Here is a "echo" command in Java.

11
The echo command
  • public class Echo
  • public static void main( String argv )
  • for( int i 0 i lt argv.length i )
  • System.out.print( Param. i
    argvi)
  • System.out.println()
  • System.exit( 0 )

12
Writing to a File Example
  • import java.io.
  • public class IOExample
  • public static void main( String args )
  • FileOutputStream fos
  • try
  • fos new FileOutputStream( args 0 )
  • while ( true )
  • int n System.in.available()
  • if ( n gt 0 )
  • byte b new byte n
  • int result System.in.read( b )
  • if ( result -1 )break
  • fos.write( b, 0, result )
  • // end while
  • catch ( IOException e ) System.err.println(
    e )
  • //end main
  • //end class

13
Reading from a File Example
  • import java.io.
  • public class IOExample2
  • public static void main( String args )
  • try
  • FileInputStream fis new FileInputStream(args
    0)
  • int n
  • while ( ( n fis.available() ) gt 0 )
  • byte b new byte n
  • int result fis.read( b )
  • if ( result -1 ) break
  • String s new String( b )
  • System.out.print( s )
  • // end while
  • catch ( IOException e ) System.err.println(
    e )
  • // end main
  • // end Type

14
Simultaneously open files
  • We can have a need for several files to be open
    at the same time, typically at least one for
    reading and one for writing. There will usually
    be an upper limit imposed by the system, perhaps
    32 files.
  • In UNIX the file close takes places automatically
    when the program terminates if the file has not
    previously been closed. In other systems,
    information being written to a file may be lost
    if the file is not closed properly.
  • Here is an example of a Java program that opens
    multiple files.
  • public class MultiFile
  • public static void main( String args )
  • FileOutputStream fos new
    FileOutputStream args.length

15
Simultaneously open files
  • try
  • for ( int i 0 i lt args.length i )
  • fosi new FileOutputStream( argsi )
  • while ( true )
  • int n System.in.available()
  • if ( n gt 0 )
  • byte b new byte n
  • int result System.in.read( b )
  • if ( result -1 ) break
  • for (int i 0 i lt args.length i)
  • fosi.write( b, 0, result )
  • catch ( IOException e ) System.err.println(
    e )
  • // end for

16
The use of files in general
  • Updating files is a common programming task. A
    file could contain details such as
  • personnel info, pay to date, tax to date, tax
    codes, etc
  • stock in the warehouse, current and minimum
    levels, etc
  • bank accounts, the owner, the balance, the
    maximum debt, etc
  • flights by the airline, booked and free seats,
    destination, timing, etc
  • In commerce, each set of related data (one
    person's record, the data for one type of stock
    item in the warehouse) is referred to as a
    "record".
  • Each complete set of related data and the means
    for accessing it from within a program would be
    represented by an object inside a Java program.
  • Each day or week or month (or instantly on
    receipt of an interactive transaction) the file
    will be updated, and a new file produced. For
    security reasons, a firm will keep a limited
    number of old copies of the file together with
    details of all subsequent transactions, so that
    the latest file can be re-created if it gets
    corrupted.
  • The information inside most files will be held in
    a definite order, e.g. ordered by personnel works
    numbers, warehouse stock number, bank customer
    account number, flight departure time, etc.

17
Updating small files
  • A typical program would go through the following
    steps to to update a small file
  • 1.read the whole of the latest master file into
    an appropriate structure (open for reading, read
    the entire file, and then close it)
  • 2.interact with the user (or use information
    stored in a data file) to update the various
    entries in the array (interact using System.in
    and System.out) (to add this week's pay, to
    decrement or increment the current warehouse
    stock values, to change the current credit in the
    bank accounts, to reserve a seat on a flight)
  • 3.write the updated information stored in the
    array into a new file (open for writing, write
    the entire file, and close).

18
Updating small files
  • If all has gone smoothly, the new file is now the
    master copy, the previous master file becomes The
    backup copy.
  • The program sequence might be
  • Declare a structure type suitable for the
    information in each record
  • Declare a big enough array of these structures
  • Open the existing master file for reading
  • Read all the information from the existing file
    into the array
  • Close the file

19
Updating small files
  • Then interact with the user using
  • while ( Ask "Any more updates? " Reply isn't no
    )
  • Ask "person? ", read person
  • Find array subscript for this person
  • Ask "details? ", read details
  • Amend entry values in array of structures
  • // end while more updates
  • Now finish off with
  • Open a new file for writing
  • Write the complete array to the new file name
  • Close the new file
  • Print any summaries as required

20
Updating large files
  • For larger files, it may not be possible to read
    the whole file into memory.
  • The program would first order the transactions so
    that they are in the same order as the entries in
    the master file we would assume that the
    transactions are now held in a file rather than
    input from a keyboard.
  • We then read the existing master file one entry
    at a time, see if that entry needs updating, and
    write that entry to the new master file.
  • In this case both old and new files (and the file
    of transactions) are open, and only one record is
    held in the program at a time.

21
Updating large files
  • The program outline might be as follows.
  • Declare a structure type for each record
  • Declare one structure variable
  • Open existing master file for reading say
    "FileInput
  • Open new master file for writing say "FileOutput
  • while ( Not at end of transaction file )
  • Read next transaction from transaction file
  • Read records from master file "FileInput",
  • copying to new master file "FileOutput
  • until this person's record found
  • Check transaction details
  • Amend record values
  • Write this person's new record to the new master
    file "FileOutput"
  • Copy the remainder of old master file "FileInput"
    to new master file "FileOutput
  • Both files should be closed here
  • Print any summaries ...

22
Updating large files
  • Alternatively, the while loop could be controlled
    by the reading from the input file, as in
  • Declare structure type for each record
  • Declare one structure variable
  • Open existing file for reading
  • Open new file for writing
  • Ask "First person to amend?
  • while ( Not reached end-of-input-file )
  • Read record from existing file
  • iif ( not person we're looking for )
  • Write record to output file
  • Continue
  • Ask "details? ", read details
  • Amend record values
  • Write this person's record to output file
  • Ask "Next person to search for?
  • // end loop to end of file

23
java.io.File
  • Platform independent definition of file and
    directory names.
  • Has methods to operate and query files and
    directories.
  • Constants to represent platform separators
  • directory
  • UNIX has / and DOS \
  • path
  • UNIX has and DOS has
  • Creating a new File Object
  • File myFile
  • myFile new File(test.dat)
  • myFile new File(/, test.dat)
  • File myDir new File(/)
  • myFile new File(myDir, test.dat)

24
java.io.File
  • String getName()
  • String getPath()
  • String getAbsolutePath()
  • String getParent()
  • boolean renameTo(File)
  • long lastModified()
  • long length()
  • boolean delete()
  • boolean exists()
  • boolean canWrite()
  • boolean canRead()
  • boolean isFile()
  • boolean isDirectory()
  • boolean mkdir()
  • String list()

25
RandomAccessFile
  • Provides random access to files.
  • Implements the DataInput and the DataOutput
    interface.
  • Instantiation with either a file name or File
    object
  • i.e RandomAccessFile myRAFile
  • myRAFile new RandomAccessFile(test.t,rw)
  • long getFilePointer()
  • void seek(long pos) // (pos 0 is the start)
  • long length()

26
Interactive transactions
  • For interactive transactions (such as airline
    bookings) there must be a way of locking an
    individual record it must not be possible for
    two customers to simultaneously request a spare
    seat, find that there is one, and attempt to both
    occupy the same single remaining seat!
  • We are then into a new level of complexity.

27
Streams
  • All fundamental I/O in Java is based on streams.
  • A stream represents a flow of data, or a channel
    of communication with (at least conceptually) a
    writer at one end and a reader at the other.
  • When you are working with terminal input and
    output, reading or writing files, or
    communicating through sockets in Java, you are
    using a stream of one type or another.
  • The diagram in the beginning has shown the large
    number of streams available in Java.
  • At a basic level you can normally use
    FileInputStream and FileOutputStream for
    manipulating files of text and InputStream and
    OutputStream for terminal access. eg System.in
    etc are defined as
  • InputStream stdin System.in
  • OutputStream stdout System.out
  • OutputStream stderr System.err

28
Stream Wrappers
  • What if we want to do more than read and write a
    load of bytes or characters?
  • Many of the InputStream, OutputStream, Reader,
    and Writer classes wrap other streams and add new
    features.
  • A filtered stream takes another stream in its
    constructor it delegates calls to the underlying
    stream while doing some additional processing of
    its own.
  • Note also the existence of stream tokenisers for
    parsing streams.

29
Streams and Readers
30
Streams for input and output
  • Abstract base classes for input and output
    functionality.
  • Defines basic set of methods.
  • Used to get data from files, other objects, etc.
  • Two base structures
  • 1.InputStream/OutputStream
  • Byte streams 8-bit
  • 2.Reader/Writer
  • Character streams
  • 16-bit UNICODE
  • Internationalization
  • Efficiency
  • Buffer (and not byte) operations
  • Better locking scheme

31
InputStream methods
  • int read()
  • int read(byte )
  • int read(byte, int, int)
  • void close
  • int available()
  • skip(long)

32
OutputStream methods
  • void write(int)
  • void write(byte )
  • void write(byte, int, int)
  • void close()
  • void flush()

33
Basic Stream Classes
  • FileInputStream -gt path to file
  • FileOutputStream
  • DataInputStream
  • byte readByte(), long readLong(), double
    readDouble()
  • DataOutputStream
  • writeByte(byte), writeLong(long),
    writeDouble(double)
  • PipedInputStream
  • PipedOutputStream

34
Readers and Writers
  • 16 bit version of Streams for UNICODE
  • InputStreamReader(is)
  • OutputStreamWriter(os)
  • BufferedReader(ir)
  • BufferedWriter(iw)
  • StringReader(string)
  • StringWriter()

35
Reading String Input Example
  • import java.io.
  • public class CharInput
  • public static void main(String argv)
  • String s
  • InputStreamReader ir
  • BufferedReader in
  • ir new InputStreamReader(System.in)
  • in new BufferedReader(ir)
  • // where does the try go ?
  • while ((s in.readLine()) !null)
  • System.out.println(Echo line)

36
Summary
  • Introduction to I/O
  • Introduction to java.io
  • Files and input/output
  • The basics of file access
  • Files in java
  • Command Line Arguments
  • The Echo Program
  • Examples
  • Writing to a File
  • Reading from a File
  • Simultaneous Access
  • General about Files
  • Updating
  • Small files
  • Large files
  • Streams
  • Input and Output Streams
  • Readers and Writers
  • Basic Stream Classes
  • Basic Readers and Writers
  • Examples
  • StreamTokenizer StringTokenizer

37
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com