CST242—File1 Streams Disk Files and I/O Streams CST242 2 1 1 2 2
3
3 3
4
4 4
5 6 5 5 6 6
7
7 7
8 9 10 8 8 9 9 10 11 10
11
Files Disk Files and I/O Streams A computerized method of storing data ... CST242 Disk Files and I/O Streams – Maintenance: Files CST242 • Adding new information A computerized method of storing data ... Files • Updating information – Maintenance: • Deleting information A computerized method of storing data ... • Adding new information – – Reporting: Maintenance: • Updating information reports • Printed Adding new information Deletingretrieval information •• On-line (on-screen/monitor—today often in a web browser) Updating information – Reporting: File and • Deleting Database information Examples • Printed reports – Reporting: Banking records including ATM's • On-line retrieval (on-screen/monitor—today often in a web browser) • Printed reports Order entry and billing File and Database Examples • On-line retrieval (on-screen/monitor—today often in a web browser) Personnel and payroll Banking records ATM's Customer, client,including contacts, etc. File and Database Examples Order entry and billing Inventory control Banking records including ATM's Personnel and payroll Course scheduling, student records including schedule as well as tuition and fees Order entry and billing Customer, client, contacts, etc. Personnel Data Hierarchy and payroll Inventory control Customer, client, contacts, etc. File Course scheduling, student records including schedule as well as tuition and fees Inventory control – A collection of a group of related records Data Hierarchy Course scheduling, student records including schedule as well as tuition and fees Record File – AllHierarchy of the data for one person or entity Data –A collection of a group of related records FileCan be thought of as a row in a table Record Field – A collection of a group of related records All ofelement the dataoffor onewithin person or entity – One data a record Record – Can be thought of as a row in awithin table the row columnor – All of the data for one person entity Field A Course – Can beTable thought Fileof as a row in a table – One element of data within a record Field Files vs.be Databases – Can thought of as a column within the row – One element of data within a record Traditionally individual files held data for each single entity … A Course Fileof asdata – Can beTable thought a column within the row – Lead to duplication of data as information was stored for multiple systems A Course Files Table – Itvs. wasDatabases almostFile impossible to extract information that involved data from more than one system Traditionally individual data files held data for each single entity … Files vs. Databases A– database Lead to duplication is a structure of data that as caninformation store information was stored about forvarious multiple types systems of entities and Traditionally individual data files held data for each single entity … their relationships – It was almost impossible to extract information that involved data from more than – Lead to duplication of data as information was stored for multiple systems one system Database Management Systems – It was almost impossible to extract information that involved data from more than A database is a structure that can store information about various types of entities and DBMS's one system are software programs that organize and manipulate data in a database their relationships A database Data from multiple is a structure systems that held caninstore single information repository about (file) various types of entities and Database Management Systems their relationships Have existed on mainframes since 1960's DBMS's are software organize and manipulate data in a database PC versions of DBMS'sprograms make thethat power of mainframe database management available Database Management Systems to desktop computing Data from multiple systems held in single repository (file) DBMS's are software programs that organize and manipulate data in a database Have – I.e.existed Microsoft on Access, mainframes Oracle, since and1960's SQL Server Data from multiple systems held in single repository (file) PC versions ofDatabase DBMS's make the power of mainframe database management available An Academic Have existed on mainframes since 1960's to desktop computing PC versions of DBMS's make the power of mainframe database management available Relational Database – I.e. Microsoft Access, Oracle, and SQL Server to desktop computing An–Academic Files in Microsoft Java Database I.e. Access, Oracle, and SQL Server Java has no specific functionality to impose structure on data in a file An Academic Database Relational Database Programmer writes code to organize the data manually into files, records and fields Relational Files in Java Database Streams Java no specific functionality to impose structure on data in a file Files inhas Java Java represents data in Unicode characters composed of two bytes Programmer writes code to organize the data manually into files, records and fields Java has no specific functionality impose structure on data in a file A stream is a series of characters to used for input or output Streams
Page 1
8
An Academic Database
9
Relational Database
CST242—File Streams
Page 2
10
Files in Java Java has no specific functionality to impose structure on data in a file Programmer writes code to organize the data manually into files, records and fields
11
Streams Java represents data in Unicode characters composed of two bytes A stream is a series of characters used for input or output In Java there are several classes used for I/O (input/output) stored in (and imported from) the java.io package
12
The Standard Output Stream Member of class System, called System.out By default, is associated with the console/ command window … – But can be changed to another output device Normally uses print() and println() to direct output to the console/monitor Output files have no fixed size … – May continue to add characters to the end of the stream to increase its size
13
The Standard Input Stream Member of class System, called System.in By default, is associated with the console/ keyboard … – Can be changed also to another input device Reads a stream of input characters An input stream pointer keeps track of the last character read … – Each new attempt to read starts at the next character
14
Output to a Sequential (Text) Disk File Requires four (4) steps: 1. Create an output stream object and associate it with a disk file 2. Give the object output functionality—the ability to ―print‖ to a file 3. Write information to the output file using methods print() and println() 4. Close the file
15
The FileWriter Class (Page 1) Used for creating output stream objects – As per Step 1 previously Associates the object to a disk file and ―opens‖ it creating a new file on the disk – Establishes a pipe (a communication link) between the program, operating system and the device (disk drive)
16
The FileWriter Class (Page 2) The filename argument in the call to the constructor method is a String which names the path and file – Current drive and directory if not specified (same location as the .class file) Found in the java.io package import java.io.FileWriter;
17
The FileWriter Class (Page 3) Format: FileWriter outputStreamObject = new FileWriter("path\filename"|fileObject); Examples: FileWriter outStream = new FileWriter("e:\\App_Data/names.txt"); FileWriter outStream = new FileWriter(".\\names.txt"); – The character ―.‖ means same directory as class FileWriter outStream = new FileWriter(fileName);
18
The PrintWriter Class
(Page 1)
17
The FileWriter Class
CST242—File Streams Format:
(Page 3)
Page 3
FileWriter outputStreamObject = new FileWriter("path\filename"|fileObject); Examples: FileWriter outStream = new FileWriter("e:\\App_Data/names.txt"); FileWriter outStream = new FileWriter(".\\names.txt"); – The character ―.‖ means same directory as class FileWriter outStream = new FileWriter(fileName); 18
The PrintWriter Class (Page 1) ―Wraps‖ around an output stream to give it additional output functionality – As per Step 2 previously The object gives write to file functionality to the print() and println() methods – To write output to the disk file as per Step 3 previously Found in the java.io package import java.io.PrintWriter;
19
The PrintWriter Class (Page 2) Format: PrintWriter printWriterObject = new PrintWriter(fileWriterObject); Example: PrintWriter outWriter = new PrintWriter(outStream);
20
Using println() and print() with a PrintWriter Object Members of an object instantiated from the PrintWriter class Writes characters to a sequential output file – An alternate to sending output to System.Out – As per Step 3 previously
21
Using println() and print() with a PrintWriter Object (Page 2) Formats: printWriterObject.println(outputObject); printWriterObject.print(outputObject); Example: outWriter.println(nameIn);
22
The close() Method (Page 1) A method of most I/O objects that closes the file stream object – As per Step 4 previously For output files: – Ensures that all data is written to disk (none remains in the RAM output buffer) – Places trailer labels (needed by O/S) at end of file
23
The close() Method (Page 2) Be certain that you close the PrintWriter object – However if you are closing FileWriter object, you actually are closing the PrintWriter object Format: inputOutputObject.close(); Examples: outWriter.close(); outStream.close();
24
The IOException Class (Page 1) May be thrown for any statement that reads from or writes to a file Super class to FileNotFoundException and EOFException All I/O operations have the potential to throw an exception (always use try…catch) Found in the java.io package import java.io.IOException;
(Page 1)
24
Examples: Format: The IOException Class
(Page 1)
outWriter.close(); catch (IOException object ) CST242—File Streams May be thrown for any statement that reads from or writes to a file 24
25
25 26 27 28
29 26 27 26 28 27 30 28 29 31
29
30 32 31
30 31
33
32
32 34
33
33
34 35
outStream.close(); Example: Super class to FileNotFoundException and EOFException tryIOException Class The (Pageto 1)throw an exception (always use try…catch) All I/O operations have the potential { be thrown for any statement that reads from or writes to a file May Found in the java.io package … Super to FileNotFoundException and EOFException importclass java.io.IOException; } I/O operations have the potential to throw an exception (always use try…catch) All The IOException Class (Page 2) catch (IOException Found in the java.io ex) package Format: {import java.io.IOException; catch … (IOException object ) The IOException Class (Page 2) Example: } Format: try FilesStreams1.java (Page 1) {catch (IOException object ) Example: FilesStreams1.java (Page 2) … try } Combining Object Definitions (Page 1) { catch (IOException ex) Stream and writer objects usually are declared together { … – Can be declared a single statement } … Combining Object Definitions (Page 2) catch (IOException ex) } { two (2) statements: The FilesStreams1.java (Page 1) … FileWriter outStream = new FileWriter("e:\\App_Data/names.txt"); FilesStreams1.java (Page 2) } PrintWriter outWriter = new PrintWriter(outStream); Become a single statement: FilesStreams1.java 1)1) Combining Object Definitions(Page (Page PrintWriter outWriter = new PrintWriter(new FileWriter("e:\\App_Data/names.txt")); Stream and writer objects usually are declared together FilesStreams1.java (Page 2) FilesStreams1.java (revised)(Page 1) – Can be declared a single statement Combining Object Definitions (Page 1) Combining 2) (an Alternate to Scanner) Input for a Object ConsoleDefinitions (Keyboard)(Page Stream Stream and writer objects usually are declared together The Thetwo default (2) statements: system input device is System.in (the keyboard) – Can be declared a single statement FileWriter = newobject FileWriter("e:\\App_Data/names.txt"); 1. Create outStream an input stream and associate it with the console/keyboard Combining Object (Page 2) ability to read characters from the PrintWriter 2. Give the outWriter objectDefinitions input = new functionality—the PrintWriter(outStream); The two a(2) statements: keyboard (i.e.statement: using the method readLine()) Become single FileWriter outStream = new 3. Read information theFileWriter("e:\\App_Data/names.txt"); keyboard PrintWriter outWriter from PrintWriter(new FileWriter("e:\\App_Data/names.txt")); PrintWriter 4. Close theoutWriter object = new PrintWriter(outStream); FilesStreams1.java (revised)(Page 1) Become a single statement: The InputStreamReader Class (Page 1) Input for a Console Stream (anFileWriter("e:\\App_Data/names.txt")); Alternate to Scanner) PrintWriter outWriter(Keyboard) = new PrintWriter(new Creates an object that reads from an input stream The default system(revised)(Page input device is System.in (the keyboard) FilesStreams1.java 1) – As per Step 1 previously 1. Create an input stream object and associate it with the console/keyboard Can only read individual charactersStream (an Alternate to Scanner) Input for a Console (Keyboard) 2. Give the object input functionality—the ability to read characters from the Found in the java.io package The default system input is System.in keyboard (i.e. using thedevice method readLine())(the keyboard) import java.io.InputStreamReader; 1. Read 3. Createinformation an input stream from the object keyboard and associate it with the console/keyboard The Class (Page 2) ability to read characters from the 2. InputStreamReader Give the 4. Close theobject objectinput functionality—the keyboard (i.e. using the method readLine()) Format: The InputStreamReader Class (Page 1) 3. Read informationinputStreamObject from the keyboard = new InputStreamReader(inputDevice); InputStreamReader Creates an object that reads from an input stream 4. Close the object Example: – As per Step 1 previously InputStreamReader inStream = new InputStreamReader(System.in); The Class (Page 1) CanInputStreamReader only read individual characters Creates an object that reads from an input The BufferedReader Class (Page 1) stream Found in the java.io package – As perjava.io.InputStreamReader; Step 1 an previously ―Wraps‖ import around input stream to give it input functionality Can only read individual characters – As per Step 2 previously The InputStreamReader Class (Page 2) Found in the java.io package Object has readLine() method Format: import – Readsjava.io.InputStreamReader; whole line of input from an input device InputStreamReader inputStreamObject = new InputStreamReader(inputDevice); – Other methods exist to read or multiple characters The InputStreamReader Classsingle (Page 2) Example: Found in the java.io package Format: InputStreamReader inStream = new InputStreamReader(System.in); import java.io.BufferedReader; InputStreamReader inputStreamObject = new InputStreamReader(inputDevice); The BufferedReader Class (Page 1) Example: The BufferedReader Class (Page 2) ―Wraps‖ around an input stream to give it input functionality InputStreamReader inStream = new InputStreamReader(System.in); Format: – As per Step 2 previously BufferedReader bufferedReaderObject = new
Page 4
39 37
―Wraps‖ around an input stream to give The BufferedReader Class (Page 2) it input functionality Format: Object has readLine() method BufferedReader bufferedReaderObject = new – BufferedReader( Reads whole lineinputStreamReaderObject of input from an input device ); – Other methods exist to read single or multiple characters Example: Found in the java.io package BufferedReader inReader = new BufferedReader(inStream); import java.io.BufferedReader; The readLine() Method (Page 1) The BufferedReader (Page A member of objects Class instantiated from2)the BufferedReader class Format: Reads an entire line of characters from a keyboard input stream until user presses the BufferedReader key andbufferedReaderObject returns the string = new BufferedReader( inputStreamReaderObject); – As per Step 3 previously Example: No quotes need to be placed around the characters BufferedReader inReader = new BufferedReader(inStream); The readLine() Method (Page 2) The readLine() Method (Page 1) Format: AbufferedReaderObject member of objects instantiated .readLine();from the BufferedReader class Reads an entire line of characters from a keyboard input stream until user presses the Example: key and returns the string nameIn = inReader.readLine(); – As per Step 3 previously FilesStreams2.java (Page 1) No quotes need to be placed around the characters FilesStreams2.java (Page The readLine() Method (Page 2) 2)
40
Format: FilesStreams3.java
35
CST242—File Streams – As per Step 2 previously
36 35
37 36
38
41 42 38 43 39 40 41 42 43
(Page 1)
bufferedReaderObject.readLine();
FilesStreams3.java (Page 2) Example: FilesStreams3.java (Page 3) nameIn = inReader.readLine();
FilesStreams2.java (Page The JFileChooser Class (Page 1) 1) Class used for selecting files with ―Open‖ FilesStreams2.java (Page 2) and ―Save‖ dialogs Optional String argument in the call to the constructor method is the path of the FilesStreams3.java (Page 1) default directory when the dialog is displayed … – The default directory is the application’s home directory if the String argument is not FilesStreams3.java (Page 2) specified FilesStreams3.java (Page 3) Found in the javax.swing package import javax.swing.JFileChooser; The JFileChooser Class (Page 1)
44
The JFileChooser Class files (Page Class used for selecting with2) ―Open‖ and ―Save‖ dialogs Optional String argument in the call to the constructor method is the path of the Format: default directory when the dialog=isnew displayed … JFileChooser fileChooserObject JFileChooser( ["path"] ); – The default directory is the application’s home directory if the String argument is not Examples: specified fileChooser = new JFileChooser("f:\\App_Data"); JFileChooser Found in the javax.swing package JFileChooser fileChooser = new JFileChooser(".\\"); import javax.swing.JFileChooser; – The second example means the same directory that contains the .class file
44 45
The Class Method (Page 2) The JFileChooser showSaveDialog() (Page 1) Format: is a member of objects instantiated from the JFileChooser object Method JFileChooser = new JFileChooser( ["path"] ); Displays a GUIfileChooserObject ―Save‖ dialog window Examples: Allows users to select the path and enter the filename of the file to be saved JFileChooser fileChooser new JFileChooser("f:\\App_Data"); Argument specifies where=the dialog will be displayed: JFileChooser fileChooser = newparent JFileChooser(".\\"); – this—centered in the dialog's window – The second example means the same directory that contains the .class file – null—centered on the screen
45 46
The showSaveDialog() showSaveDialog() Method Method (Page (Page 2) 1) The Method is a member of objects instantiated the was JFileChooser object or Returns an int which specifies which button from in dialog clicked, Displays a GUI ―Save‖ dialog window Allows users to select path and by enter the filename of theconstants: file to be saved Programmer may test the return value comparing it to static Argument specifies where the dialog will be – JFileChooser.APPROVE_OPTION (value 0) displayed: – this—centered in the dialog's parent JFileChooser.CANCEL_OPTION (valuewindow 1) null—centered on theexample: screen – Consider the following
Page 5
Argument the dialog will be in displayed: Returns anspecifies int whichwhere specifies which button dialog was clicked, or
– this—centered in the dialog's parent window CST242—File Streams 46
47
47
Programmer – null—centered may on testthe return screen value by comparing it to static constants: – JFileChooser.APPROVE_OPTION (value2) 0) The showSaveDialog() Method (Page – JFileChooser.CANCEL_OPTION (value 1) Returns an int which specifies which button in dialog was clicked, or Consider the following example: if (result ==may JFileChooser.APPROVE_OPTION) Programmer test return value by comparing it to static constants: The – JFileChooser.APPROVE_OPTION showSaveDialog() Method (Page (value3) 0) – JFileChooser.CANCEL_OPTION (value 1) Format: JFileChooserObject Consider the following example: .showSaveDialog( this/null); if (result == JFileChooser.APPROVE_OPTION) Examples: result = fileChooser.showSaveDialog(null); The showSaveDialog() Method (Page 3) if ( fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION ) Format:
48
The JFileChooserObject getSelectedFile() .showSaveDialog( Method (Pagethis/null); 1) Examples: A method of a JFileChooser object that returns the object’s path and filename selected by result the = user fileChooser.showSaveDialog(null); in an ―Open‖ or ―Save‖ dialog Returns if ( fileChooser.showSaveDialog(null) an object of reference type File ==(not JFileChooser.APPROVE_OPTION a String) )
49 48
The getSelectedFile() Method (Page 2) 1) A method of a JFileChooser object that returns the object’s path and filename selected Format: by the user in an ―Open‖ or ―Save‖ dialog fileChooserObject .getSelectedFile(); Returns an object of reference type File (not a String) Example: File fileName = fileChooser.getSelectedFile(); The getSelectedFile() Method (Page 2)
49 50
50 51
51
52
52
53 54
55 56 53 54 55 56 57
The File Class Format: (Page 1) .getSelectedFile(); AfileChooserObject reference type that encapsulates (stores) information about a file Example: – I.e. filename, path, etc. File fileName = fileChooser.getSelectedFile(); Found in the java.io package import java.io.File; The File Class (Page 1) Thereference A File Class type that encapsulates (Page (stores) 2) information about a file – I.e. filename, path, etc. Format: Found in the java.io File fileObject = newpackage File("path/filename") import java.io.File; Examples: File fileName The File Class = File("f:\\App_Data/names.txt"); (Page 2) File fileName = fileChooser.getSelectedFile(); Format:
The File getName() fileObject =Method new File("path/filename") Examples: A method of a File object that returns the object’s filename as a String File fileName = File("f:\\App_Data/names.txt"); Format: File fileName = fileChooser.getSelectedFile(); fileObject .getName(); Example: The getName() Method fileName.getName().equals("") ); the object’s filename as a String Aif(method of a File object that returns Format: FilesStreams4.java (Page 1) fileObject.getName(); FilesStreams4.java (Page 2) Example: FilesStreams4.java (Page if( fileName.getName().equals("") ); 3) The FileReader Class FilesStreams4.java (Page 1) Creates an object that reads from an input FilesStreams4.java (Page 2) stream from a disk file – As opposed to input from the console FilesStreams4.java Found in the java.io package (Page 3) import java.io.FileReader; The FileReader Class (Page 1) Creates The FileReader an object Class that reads from (Page an input 2) stream from a disk file – As opposed to input from the console Format: Found in thefileReaderObject java.io package = new FileReader("path/filename"/fileObject); FileReader import java.io.FileReader; Examples:
Page 6
56 58 59
The FileReader Classpackage (Page Found in the java.io FilesStreams5.java (Page 1) 2) 1)
59 60 57 60
FilesStreams5.java 2)1) The showOpenDialog (Page – As opposed to input Method from the(Page console The FileReader Class (Page 2) Method a member ofMethod objects instantiated Found inisthe java.io package The showOpenDialog (Page 1) from the JFileChooser object Format: a GUI ―Open‖ dialog window Displays import java.io.FileReader; Method is a member of objects instantiated frompath the /JFileChooser object ); FileReader = new FileReader(" filename "/fileObject Allows usersfileReaderObject to select path and filename of the file to be opened Displays a GUI ―Open‖ dialog window The FileReader (Page 2) (specifies where dialog will be displayed): Examples: Argument is theClass same as showSaveDialog Allows users to select path and of the file to be opened Format: FileReader inputStream = new filename FileReader("f:\\App_Data/names.txt"); – this—centered in the dialog's parent window Argument isfileReaderObject the same as=showSaveDialog (specifies dialog will be displayed): = new FileReader(" pathwhere /filename "/fileObject ); FileReader inputStream new FileReader(fileName); – null—centered on the screen – this—centered in the dialog's parent window Examples: FilesStreams5.java (Page The showOpenDialog (Page1)2) – null—centered on theMethod screen FileReader inputStream = new FileReader("f:\\App_Data/names.txt"); Format: FilesStreams5.java FileReader inputStream = new(Page FileReader(fileName); The showOpenDialog Method (Page2)2) JFileChooserObject.showOpenDialog( this/null ); Format: FilesStreams5.java The showOpenDialog Method(Page (Page1)1) Example: JFileChooserObject .showOpenDialog( this/null ); the JFileChooser object Method a member of objects(Page instantiated from result =isfileChooser.showOpenDialog(null); FilesStreams5.java 2) Example: Displays a GUI dialog window Return value is ―Open‖ an int that indicates which button was clicked, or result = fileChooser.showOpenDialog(null); The showOpenDialog Method (Page 1)of the file to be opened Allows users to select path and filename if (result == JFileChooser.CANCEL_OPTION) Return is an intof that indicates which (specifies button was clicked, Methodvalue is ais member instantiated from the JFileChooser object Argument the same asobjects showSaveDialog where dialog will beordisplayed): FilesStreams6.java (Page 1) if (resulta== Displays GUIJFileChooser.CANCEL_OPTION) ―Open‖ window – this—centered in thedialog dialog's parent window Allows users to select path and(Page filename – null—centered on the screen FilesStreams6.java 1) of the file to be opened 2) Argument is the same as showSaveDialog (specifies where dialog will be displayed): The showOpenDialog Method (Page3) 2) FilesStreams6.java – this—centered in the dialog's(Page parent2) window Format: – null—centered on the screen(Page 1) FilesStreams6.java 3) FilesStreams7.java JFileChooserObject.showOpenDialog( this/null ); The showOpenDialog Method(Page (Page2) Example: FilesStreams7.java 1)2) Format: result = fileChooser.showOpenDialog(null); FilesStreams7.java (Page 3) 2) JFileChooserObject .showOpenDialog( this/null ); was clicked, or Return value is an int that indicates which button Example: FilesStreams7.java (Page 3) Sequential Master File Update Processing (Page 1) if (result == JFileChooser.CANCEL_OPTION) result = fileChooser.showOpenDialog(null); Batch processing processing several transactions at the(Page same 1) time FilesStreams6.java Sequential Masterinvolves File Update (Page Processing 1) Return value is an transaction int that indicates button was clicked, or – Results of each are notwhich immediately available when the transaction is Batch processing involves processing several transactions at the same time FilesStreams6.java (Page if being (resultentered; == JFileChooser.CANCEL_OPTION) there is a time delay2) – Results of each transaction are not immediately available when the transaction is Transactions are accumulated for a certain FilesStreams6.java (Page 1) period (say for day or a week) and updates being entered; there is a time delay3) are made at the end of that period Transactions are accumulated for a certain FilesStreams6.java 2) period (say for day or a week) and updates FilesStreams7.java (Page 1) Sequential Master File Update Processing (Page 2) are made at the end of that period FilesStreams6.java 3) FilesStreams7.java (Page 2) There are three files involved in the master update of sequential files: 2) Sequential Master File Update Processing (Page – Old master file—file containing a company’s records, i.e. inventory, employee, FilesStreams7.java 1) 3) There are three files involved in(Page the master update of sequential files: accounts, etc. (currently out of date) – Old master file—file a company’s records, i.e. inventory, employee, FilesStreams7.java (Page 2) activity Sequential Master Filecontaining Update Processing 1) needed – Transaction file—contains the periodic of transactions(Page that record accounts, etc. (currently out of date) changes to the involves master file Batch processing processing several transactions at the same time FilesStreams7.java (Page 3) activity of transactions that record – Transaction file—contains the periodic needed – New master file—merging of old master and transaction files into new (up-to-date) Results transaction changesoftoeach the master file are not immediately available when the transaction is Sequential Masterthere File isUpdate Processing (Page 1) master being entered; a time delay – New master file—merging of old master and transaction files into new (up-to-date) Batch processing involves processing several transactions theorsame timeand updates Transactions are accumulated forProcessing a certain period (say forat day a week) Sequential Master File Update master are made at of that period – Results of the eachend transaction are not immediately available when the transaction is Sequential Masterthere File Update Processing (Page 3) being entered; a time delay Sequential Master File isUpdate Processing (Page 2) Update processing: Transactions are accumulated forProcessing a certain period (say for day or a week) and updates Sequential Master File Update (Page There are three files involved in the master update of sequential files: 3) are made at the end of that period – Update existing records Update processing: – Old master file—file containing a company’s records, i.e. inventory, employee, – Add newMaster recordsFile Update Processing Sequential (Page 2) – Update accounts, existing etc. (currently records out of date) – Delete obsolete records There are files involvedthe in the master update sequentialthat files:record needed – Add Transaction newthree records file—contains periodic activity of of transactions Sequential changes Master to the master File Update file Processing (Page 4) – Delete Old master obsolete file—file records containing a company’s records, i.e. inventory, employee, accounts, etc. (currently out – New master file—merging of of olddate) master and transaction files into new (up-to-date) Requires: Sequential Master File Update Processing (Page 4) master Transaction the periodic activity of transactions needed –A unique keyfile—contains field, i.e. Customer Number, Employee Number, that Part record Number, etc. Requires: changes to the master file – Both Transaction file and Master File must be in same sequence Sequential Master File Processing – A unique keyfile—merging field, i.e.Update Customer Number, Employee Number, Partnew Number, etc. – master master and transaction files into (up-to-date) – New The New Master also mustof beold kept in sequence – Both Transaction file and Master File must be in same sequence Sequential (Page 3) master Master File Update Processing Sequential Master File Update Processing (Page 5) – The New Master also must be kept in sequence Update processing: Sequential Master File Update Processing OLD MASTER key > TRANSACTION key – Update existing records Sequential Master File Update Processing (Page 5) – Add Transaction record to New Master File Sequential Master File Update Processing (Page 3) – Add new records OLD MASTER key > TRANSACTION key OLD MASTER key < TRANSACTION key
CST242—File Streams Creates an object that reads from an input stream from a disk file import java.io.FileReader;
57
58 61
59 61 58 60 59
60 62 62 63 61 63 64
64 65 61 65 66 66 67 67 68 62 68 63 62 64 63 65 69 64 66 69 65 67 66 68 67 68 70 70 71 69 71 69 72 72 70 71 73 70 73 71
Page 7
89 90
– Delete obsolete records MasterUpdate.java
(Page 1)
CST242—File 72 Streams Sequential Master File Update Processing 90 91 91 92 92 93 93 94 73 94 95 95 96 96 97 97 98 98 99 74 99 75 76 77 100 78 100 101 79 101 80 81 102 82 102 83 84 85 103 86 103 87 88 89 104 90 104 91 92 93 94 105 95 105 96
97 106 98
106 99
107
(Page 4) 1) MasterUpdate.java (Page 2) Requires: – A unique key field, i.e. Customer Number, Employee Number, Part Number, etc. MasterUpdate.java (Page 2) 3) – Both Transaction file and Master File must be in same sequence MasterUpdate.java (Page 4) 3) – The New Master also must be kept in sequence 4) MasterUpdate.java (Page 5) Sequential Master File Update Processing (Page 5) OLD MASTER key > TRANSACTION MasterUpdate.java (Page key 5) 6) – Add Transaction record to New Master File MasterUpdate.java (Page 7) 6) OLD MASTER key < TRANSACTION key 7) File MasterUpdate.java (Page 8) – Copy Old Master Record to New Master OLD MASTER key = TRANSACTION key MasterUpdate.java (Page 8) 9) – Update Old Master Record with data from Transaction Record and copy to New MasterUpdate.java Random (Page 1) 9) MasterAccess File Files Refers to ability to access records from Random Access Files (Page 1)a data file at random – The opposite of random access is sequential access in which data must be accessed Refers to ability to access records from a data file at random by passing through all intervening points – The opposite of random access is sequential access in which data must be accessed Enables reading or writing information from or to any point in the file by passing through all intervening points – In a sequential-access file, must be accessed starting from the beginning of the file Enables reading or writing information from or to any point in the file Random Access Files – In a sequential-access file, must be accessed starting from the beginning of the file Random Access Files (Page 2) Disks areAccess random access media(Page 2) Random Files – Tapes are sequential access media Disks are random access media Sometimes also called direct access – Tapes are sequential access media The RandomAccessFile Class (Page 1) Sometimes also called direct access Objects instantiated fromClass this class have1) the ability to read and write randomly The RandomAccessFile (Page Similar to FileWriter and FileReader in that a file can be specified on the system to Objects instantiated from this class have the ability to read and write randomly open when it is created it Similar to FileWriter and FileReader in that a file can be specified on the system to – Use either ―path\filename‖ string or File object open when it is created it The RandomAccessFile Classstring (Page 2)object – Use either ―path\filename‖ or File When opening a RandomAccessFile, indicate The RandomAccessFile Class (Page 2) whether file just will be read from (―r‖) or also written to (―rw‖) When opening a RandomAccessFile, indicate whether file just will be read from (―r‖) or – Must be able to read a file in order to write it also written to (―rw‖) Found in the java.io package – Must be able to read a file in order to write it import java.io.RandomAccessFile; Found in the java.io package The RandomAccessFile Class (Page 3) import java.io.RandomAccessFile; MasterUpdate.java (Page 1) Format: The RandomAccessFile Class (Page 3) RandomAccessFile randomAccessObject MasterUpdate.java (Page 2) = new RandomAccessFile("path/filename" | Format: fileObject, "r"/"rw"); RandomAccessFile randomAccessObject = new RandomAccessFile("path/filename" | MasterUpdate.java (Page 3)methods – The strings ―r‖ or ―rw‖ are the access fileObject, "r"/"rw"); Example: MasterUpdate.java (Page 4)methods – The strings ―r‖ or ―rw‖ are the access RandomAccessFile courseFile = new RandomAccessFile("f:/creditFile.dat", "rw"); Example: MasterUpdate.java (Page 5) Random Access FilecourseFile Processing 1) RandomAccessFile = new(Page RandomAccessFile("f:/creditFile.dat", "rw"); MasterUpdate.java (Page 6) After a random file is open, common read and write methods are defined in the Random Access File Processing (Page 1) DataInput and DataOutput interfaces to perform I/O MasterUpdate.java (Page 7) After a random file is open, common read and write methods are defined in the – Class RandomAccessFile implements both DataInput and DataOutput DataInput and DataOutput interfaces MasterUpdate.java (Page to 8) perform I/O Random File Processing (Page – Class Access RandomAccessFile implements both2)DataInput and DataOutput MasterUpdate.java (Page 9) For example: Random Access File Processing (Page 2) Random Access Files (Page 1) – The writeInt() writes four bytes of numeric integer data to the file For example: – The readInt() reads four bytes of numeric integer from the file Refers to ability to access records a datainteger file at data random – The writeInt() writes four bytes from of numeric data to the file There are write of andrandom read methods every primitive data type data must be accessed – isfor sequential access in which – The The opposite readInt() reads four access bytes of numeric integer data from the file by passing through all intervening points The Fileare Pointer There write and read methods for every primitive data type Enables reading or writing information from or to any point in the file
Page 8
110 106
The After Seek a random Method file open, common (Page read 1) and Random Access FileisProcessing (Page 2) write methods are defined in the
DataInput and interfaces to CST242—File 111 Streams A The method Seek Method of theDataOutput RandomAccessFile (Page class 2) perform that setsI/O moves the file-pointer position For example: 106
111 107
107 112 113 114 108 112 115 109 113 116 110 108 117 114 109 115 118 110 116 119 120 117 111 121 118 122 119 111 120 123 121 122 112 123 113 124 114 112 125 115 113 126 116 114 124 127 117 115 125 118 116 126 119 117 127 120 118 121 119 122 120 128 123 121 122 123 128
129 124 125 126 124 129
– Class RandomAccessFile implements both DataInput and DataOutput – in bytes from the beginning of file Format: – Measured The writeInt() writes four bytes of numeric integer data to the file – which thebytes next);read or write operation begin randomAccessObject .seek( long Random AccessatFile Processing 2)integer – The The location readInt() reads four of (Page numeric datawill from the file The offset position often is calculated based upon which record accessed next – long is a long integer value or variable, or an arithmetic expression that evaluates to For example: There are write and read methods for every primitive data type is to be a long – The writeInt() of numeric integer data to the file The Seek Methodwrites four bytes (Page 2) The File Pointer Examples: – The readInt() reads four bytes of numeric integer data from the file Format: RandomAccessFile supports the notion of a file pointer: courseFile.seek(4); There are write and read methods for every primitive data type randomAccessObject .seek( long); – Indicates the current location in the file); courseFile.seek(4 * (courseNumber - 1) – a long integer value ororvariable, anfile arithmetic The File is Pointer – long When the file is first created opened,or the pointer isexpression set to zerothat (0),evaluates indicatingto The a Data long the beginning of supports the file the notion of a file pointer: RandomAccessFile Examples: – Indicates Calls to read the and current writelocation methods in the advances file the file pointer by the number of bytes The Index courseFile.seek(4); read or written – When the file is first created or opened, the file pointer is set to zero (0), indicating FilesStreams9.java (Page- 1) courseFile.seek(4 (courseNumber 1) ); the beginning of*the file FilesStreams8.java (Page 1) – Calls advances the file pointer by the number of bytes The FilesStreams9.java Datato read and write methods (Page 2) FilesStreams8.java (Page 2) read or written The Index FilesStreams9.java (Page 3) The Seek Method (Page 1) FilesStreams8.java FilesStreams9.java FilesStreams10.java (Page (Page 1) that 1) sets moves the file-pointer position A method of the RandomAccessFile class FilesStreams8.java (Page 2) – Measured in bytes from the beginning file FilesStreams9.java FilesStreams10.java (Page (Page 2) of 2) The Seek Method (Page 1) – The location at which the next read or write operation will begin FilesStreams9.java FilesStreams10.java (Page (Page 3) that 3) sets moves the file-pointer position A method the RandomAccessFile class The offset of position often is calculated based upon which record is to be accessed next – Measured in bytes from the beginning of 1) file The Data FilesStreams10.java (Page The Seek Method (Page 2) – The location at which the next read or write operation will begin Format: FilesStreams10.java Record Size (Page 2) The offset position often is calculated based upon which record is to be accessed next randomAccessObject.seek(long); FilesStreams10.java The Index (Page The Seekis Method (Page 2) or3)an arithmetic expression that evaluates to – long a long integer value or variable, Format: The alength() Data long Method for a RandomAccessFile Object Examples: randomAccessObject .seek( long); For a RandomAccessFile object, returns the length of the file measured in bytes Record Size – long is a long integer value or variable, or an arithmetic expression that evaluates to courseFile.seek(4); Format: The aIndex long courseFile.seek(4 * (courseNumber randomAccessFileName .length(); - 1) ); Examples: Example: The length() Data Method for a RandomAccessFile Object courseFile.seek(4); courseFile.seek( courseFile.length() ); the length of the file measured in bytes For a RandomAccessFile object, returns The Index courseFile.seek(4 * (courseNumber - 1) ); Format: FilesStreams11.java (Page 1) The FilesStreams9.java Data (Page 1) randomAccessFileName .length(); FilesStreams11.java (Page 2) Example: The Index FilesStreams9.java (Page 2) FilesStreams11.java 3) courseFile.seek( courseFile.length()(Page ); FilesStreams9.java (Page 3) 1) FilesStreams11.java The getChars() Method for a String (Page Object 1) (Page 1) FilesStreams9.java FilesStreams10.java (Page (Page 2) 1) Copies characters from the string into a destination character array FilesStreams11.java (Page 2) Format: FilesStreams9.java FilesStreams10.java (Page (Page 3) 2) FilesStreams11.java (Page 3), destBegin); stringObject.getChars(srcBegin, srcEnd , dest FilesStreams10.java (Page 3) 1) – srcBegin —index of the for firstacharacter to copy The getChars() Method String Object (Page 1) – srcEnd —index after the last character in the string to copy The Data FilesStreams10.java (Page 2) Copies characters from the string into a destination character array – dest—the destination char array Format: FilesStreams10.java Record Size (Page 3) – destBegin—start offset in the ,destination array. stringObject .getChars( srcBegin srcEnd, dest , destBegin); The Data Index The – srcBegin getChars() —index Method of the for firstacharacter String Object to copy (Page 2) – srcEnd —index after for the alast character in the string to copy The length() Method RandomAccessFile Object Format: Record Size – dest —the destination char array stringObject .getChars(srcBegin srcEnd,the dest , destBegin For a RandomAccessFile object,,returns length of the);file measured in bytes The Index – destBegin—start offset in the destination array. Example: Format: The length() Method for a RandomAccessFile Object (Page 2) outString.getChars(0, length, randomAccessFileName .length(); The getChars() Method for a chars, String0); Object For – The a RandomAccessFile variable chars is aobject, char array returns the length of the file measured in bytes Example: Format: Format: courseFile.seek( courseFile.length() ); , dest, destBegin The stringObject writeChars() .getChars( Method srcBegin for a, srcEnd RandomAccessFile Object ); (Page 1) randomAccessFileName .length(); Example: FilesStreams11.java (Page 1) Writes a string to the file as a sequence of characters … Example: outString.getChars(0, length, chars, 0); – Each character is written separately to the data output stream as though were being FilesStreams11.java (Page 2) courseFile.seek( courseFile.length() – written The variable by thechars writeChar() is a charmethod array );contained within a loop FilesStreams11.java (Page 1) 3) The write operation starts at the position of theObject file pointer The writeChars() Method for a current RandomAccessFile (Page 1)
Page 9
Format:
CST242—File Streams stringObject.getChars(srcBegin, srcEnd, dest, destBegin); Example: outString.getChars(0, length, chars, 0); – The variable chars is a char array 129
The writeChars() Method for a RandomAccessFile Object (Page 1) Writes a string to the file as a sequence of characters … – Each character is written separately to the data output stream as though were being written by the writeChar() method contained within a loop The write operation starts at the current position of the file pointer
130
The writeChars() Method for a RandomAccessFile Object (Page 2) Format: randomAccessFileName.writeChars(String); Example: outFile.writeChars( new String(chars) ); – The variable chars is a char array and String is a call to String constructor that takes a char array
131
The DataInput and DataOutput Interfaces (Page 1) DataInput—an interface that provides for reading bytes from a binary stream – The bytes may be reconstructed into any of the Java primitive types DataOutput—an interface that provides for writing bytes to a binary stream – Data converted from any of the Java primitive types back to a series of bytes
132
The DataInput and DataOutput Interfaces (Page 2) The RandomAccessFile class implements both the DataInput and DataOutput … Therefore subtyping allows assigning any RandomAccessFile object to be assigned to either a DataInput or DataOutput object … – Effectively a RandomAccessFile object ―is a‖ DataInput object … – Additionally a RandomAccessFile object ―is a‖ DataOutput object
133
The DataInput and DataOutput Interfaces Found in the java.io package import java.io.DataInput; import java.io.DataOutput;
134
The readChar() Method for a RandomAccessFile Object Reads a single character from an object instantiated from class RandomAccessFile Format: randomAccessFileObject.readChar(); Example: chars[ctr] = inFile.readChar();
135
FixedLengthStringIO.java
(Page 1)
136
FixedLengthStringIO.java
(Page 2)
137
FixedLengthStringIO.java
(Page 3)
138
FilesStreams12.java
(Page 1)
139
FilesStreams12.java
(Page 2)
140
FilesStreams12.java
(Page 3)
141
Project 7: Chapter 17 (Exercise No. 17.7, pp. 753-754)
142
Project 7: Chapter 17 (Exercise No. 17.7, pp. 753-754)
143
Project 7: Chapter 17 (Exercise No. 17.7, pp. 753-754)
(Page 3)
Page 10