Intro to the AS/400 - Florida State College at Jacksonville

Intro to the AS/400 - Florida State College at Jacksonville

Intro to Programming & Algorithm Design Data Files Assg This presentation can be viewed on line in a file named: Copyright 2003 by Janson Industries ch09.IntrotoProg.Files.ppt 1 Objectives Explain Advantages of files How to process files Show how to use files in Java

2 Copyright 2014 by Janson Industries File Everything on a computer is stored in files Images Documents Web pages Spreadsheet

Flowcharts Java source code Java bytecode 3 Copyright 2014 by Janson Industries Data File We are talking about data files Inventory data

Customer data Sales data Kind of like an array but more permanent When pgm stops data still exists 4 Copyright 2014 by Janson Industries File Advantages Instead of entering data every time a pgm is run, user can enter once and pgm can save to a file

Data can then be accessed at a later time This is how apps remember info Browser favorities Amazon purchase history Video game high scores 5 Copyright 2014 by Janson Industries Data Files

Are stored on secondary storage Hard drive Flash drive Cloud drive A program can put data into a file (write to the file) or retrieve a copy of the data from the file (read the file) 6 Copyright 2014 by Janson Industries Files

Programs read files just like they read data from the command line Can read the entire line Can read one word i.e. All the text up to the next space Programs write to files just like they write to the console With a carriage return Without carriage return 7

Copyright 2014 by Janson Industries Files When writing, some languages will overwrite any existing data in a file Others let you append data Before a file can be written to or read from, it must be opened Any data written to a file will be saved when the file is closed by the progam 8 Copyright 2014 by Janson Industries Files In pseudocode you must declare a program file name

At the same time the file must also be defined as input or output Lastly, the program file name has to be associated with the file's physical name 9 Copyright 2014 by Janson Industries Files Windows file's physical names have a prefix and a suffix Prefix can have many parts (separated by periods) but the suffix indicates the type of info in the file Dear.John.docx

My.First.Pgm.java My.Latest.Greatest.Selfie.jpeg 10 Copyright 2014 by Janson Industries Writing to Files Declare the file as an output file The program file name and the file's physical name are tied together in the open statement Declare OutputFile customerFile Open customerFile "Customer.dat" Write customerFile "Joe Customer" Write customerFile "1 Main St." Write customerFile "Enid, OK 34343" Close customerFile

11 Copyright 2014 by Janson Industries Reading Files Declare the program file name as input Associate it with the physical file name Read the file Results in the 3 variables holding the file data Copyright 2014 by Janson Industries Declare String custName, custStreet, custCSZ Declare InputFile customerFile

Open customerFile "Customer.dat" Read customerFile custName Read customerFile custStreet Read customerFile custCSZ Close customerFile 12 Appending to Files In the declare, identify the mode as AppendMode So, running the following Results in Declare OutputFile AppendMode customerFile Open customerFile "Customer.dat" Write customerFile "Mary Buyer" Write customerFile "2 Oak St Write customerFile "Muncie, IN 54545"

Close customerFile 13 Copyright 2014 by Janson Industries Using Loops to Process Files Like arrays, loops very useful for accessing data in files Unlike arrays, files can have variable amounts of data No length variable for files Most file systems have a way to determine if the end of the file has been reached Copyright 2014 by Janson Industries

14 Using Loops to Process Files Copyright 2014 by Janson Industries In pseudocode, use the eof (end of file) function eof(customerFile) will return a true if the last record/line has been read Can use eof in a while loop to process all the data in a file 15 Using Loops to Process Files Copyright 2014 by Janson Industries

Assuming Customer.dat has the following info 16 Using Loops to Process Files To display a mailing list like this: Joe Customer 1 Main St. Enid, OK 34343 Mary Buyer 2 Oak St. Muncie, IN 54545 Terry Smith 3 Pine Ave. Palatka, FL 32273 Copyright 2014 by Janson Industries Pat Jones 4 Lake Dr. Erie, PA

23232 17 Using Loops to Process Files Module main() Declare Integer ctr Declare String tempVariable Declare InputFile customerFile Open customerFile "Customer.dat" While NOT eof(customerFile) For ctr = 1 to 3 Read customerFile tempVariable Display tempVariable End For Display " " End While Close customerFile 18 End Module Copyright 2014 by Janson Industries Raptor

Flowgorithm cannot process files So new tool - Raptor Like Flowgorithm, can execute the flowchart Copyright 2016 by Janson Industries Several differences between Flowgorithm and Raptor 19 Raptor No declare function

Only global variables Copyright 2016 by Janson Industries Must specify Declares as commments No passing variables between modules No distinction between modules and functions Input function also has output function for prompt text 20 Raptor For example, heres a Raptor

FC that adds two numbers 21 Copyright 2016 by Janson Industries Raptor When executed result is: 22 Copyright 2016 by Janson Industries http://raptor.martincarlisle.com/ 23 Copyright 2016 by Janson Industries Scroll down 24 Copyright 2016 by Janson Industries Click drop down button, select Save As, then specify your thumb drive

Click Save 25 Copyright 2016 by Janson Industries Double click to start install 26 Copyright 2016 by Janson Industries 27 Copyright 2016 by Janson Industries 28 Copyright 2016 by Janson Industries Specify thumb drive location (this way you can run from any computer) 29 Copyright 2016 by Janson Industries 30 Copyright 2016 by Janson Industries

31 Copyright 2016 by Janson Industries To run, double click raptor.exe 32 Copyright 2016 by Janson Industries Or from the All Apps menu, select Raptor 33 Copyright 2016 by Janson Industries This is where the flowchart is defined Output shown here 34 Copyright 2016 by Janson Industries Raptor

To add a symbol, click to select 35 Copyright 2016 by Janson Industries Raptor then click in flowchart where to put the symbol You can also drag/drop 36 Copyright 2016 by Janson Industries Raptor To edit symbol (add function) click symbol 37 Copyright 2016 by Janson Industries Raptor Then click Edit and Edit Selection 38 Copyright 2016 by Janson Industries Raptor

Enter statement(s), click done 39 Copyright 2016 by Janson Industries Raptor To run, click the Execute to Completion button 40 Copyright 2016 by Janson Industries Raptor Output displayed in Console 41 Copyright 2016 by Janson Industries Raptor Raptor has two symbols for I/O

One for input One for output The input symbol actually does an output first A text prompt is displayed Then the input is done 42 Copyright 2016 by Janson Industries Raptor Can also just double click the symbol to edit 43 Copyright 2016 by Janson Industries Raptor

Enter prompt text, variable to hold info, click Done 44 Copyright 2016 by Janson Industries Raptor Added an output symbol Notice Raptor uses + not & to concatenate 45 Copyright 2016 by Janson Industries Raptor As each symbol is executed, its outlined in green 46 Copyright 2016 by Janson Industries Raptor When input symbol reached, program execution halts and a window is displayed with the prompt text and an input field 47

Copyright 2016 by Janson Industries Raptor User should enter the input and click OK 48 Copyright 2016 by Janson Industries Raptor Program finishes executing and results displayed in console To insert a comment, right click a symbol and select Comment 49 Copyright 2016 by Janson Industries Files in Raptor To read, use the Input function but must first identify the file as the source of the input

Done by calling the Redirect_Input function I.e. not the keyboard/console Redirect_Input("E:/Customer.dat") To write to a file use the Redirect_Output function Copyright 2014 by Janson Industries 50 Using File Loops in Raptor Raptor has an End_Of_Input function that is used to control a loop

To close a file, set the redirect to false Copyright 2014 by Janson Industries Redirect_Input(false) 51 Using File Loops in Raptor Start Redirect_Input("E: / Customer.dat") Loop EOF loop to read all records Yes End_Of_Input

No ctr 1 Loop Loop to read the three records for each Copyright 2014 by Jansoncustomer Industries Yes ctr>3 52 Using File Loops in Raptor Reads and displays a record No

""GET tempVariable PUT tempVariable ctr ctr + 1 Blank line separating each customers data Close the file PUT " " Redirect_Input(false) End Copyright 2014 by Janson Industries 53 Using File Loops in Raptor Results Copyright 2014 by Janson Industries

54 Files in Java To read, still use a Scanner and its next(), nextLine, nextDouble, etc. methods Need to tie the scanner to the file Done when creating the Scanner Need to import java.io.File; Scanner customerFile = new Scanner(new File("E:/Customer.dat")); Copyright 2014 by Janson Industries

55 Files in Java If the file doesn't exist, creating the scanner will cause a File Not Found Exception Two ways to handle Put the following code in the header of the method And import java.io.IOException; public static void main(String[] args) throws IOException { Copyright 2014 by Janson Industries 56

Files in Java Or you can enclose the statement as follows And import java.io.FileNotFoundException; try { customerFile = new Scanner(new File("E:/Customer.dat")); } catch (FileNotFoundException e) { e.printStackTrace(); } Copyright 2014 by Janson Industries 57 Using File Loops in Java The Scanner has a method called hasNext

Will return true if there is more data To close a file, use the Scanner's close method customerFile.close( ); Copyright 2014 by Janson Industries 58 import import import public java.io.File; java.io.IOException; java.util.Scanner; class FileLoop {

Using File Loops in Java public static void main(String[] args) throws IOException { //Declare variables int ctr; String tempVariable = new String(); //Declare objects and variables needed to read the file Scanner customerFile = new Scanner(new File("E:/Customer.dat")); while(customerFile.hasNext()) { for(ctr = 1; ctr <4; ctr++) { //Reads and displays one record from the file tempVariable = customerFile.nextLine(); System.out.println(tempVariable); } //Blank line for readablity System.out.println(""); } //Close the file Copyright 2014 by Janson Industries 59

Using File Loops in Java Copyright 2014 by Janson Industries 60 Modifying Files Text files not always easy to add to or modify Copyright 2014 by Janson Industries That's why there are Databases Some languages allow you to append to the file but some don't But no language has an easy

way to modify 61 Modifying Files To add when language doesn't allow adding, have to: Read all the records from the file Write them to a temp file Get the new data and write it to the temp file Then read all the records from the temp file

Write them to the original file Copyright 2014 by Janson Industries I.e. write over what was in the original file 62 Modifying Files - Adding Customer.dat Old Data New User Data Old and New Data Copyright 2014 by Janson Industries AddPgm Old Data

TempFile.dat New Data AddPgm AddPgm Old and New Data 63 Adding a Record Fortunately, Java allows appending so we won't have to mess with the temporary file when adding

But Raptor doesn't!! Also, we should check the file and make sure that a record doesn't already exist for the "new" data Have to search the entire file before adding a record Copyright 2014 by Janson Industries 64 Modifying a Record User specifies record to modify Read and write all the records from original file to temp until the record to modify is read Prompt the user with the old data

Get new data and write it to temp Copyright 2014 by Janson Industries Read rest of original records and write them to temp Copy temp back to original 65 Modifying a Record User Data To Modify AddPgm Customer.dat Data AddPgm Data TempFile.dat

Records Records Up to the Up to the one to modify one to modify Old Data AddPgm User New Data Copyright 2014 by Janson Industries New Data 66 Modifying a Record Rest of Rest of Customer.dat AddPgm TempFile.dat Data

Data Customer.dat All Data AddPgm All Data TempFile.dat 67 Copyright 2014 by Janson Industries Modifying Files Will design a program to allow users to add, modify or display a customer's information

If user wants to add a customer, will check that info for that customer does not already exist Copyright 2014 by Janson Industries If info does exist, will not allow user to add 68 Module main() Declare String option = "" While option NOT equal 4 Display "What would you like to do? Enter:" Display "1 to add a customer" Display "2 to modify a customer" Display "3 to display a customer" Display "4 to end the pgm" Input option If option = "1" Then addRecord() Else If option = "2" Then

modifyRecord() Else If option = "3" Then displayRecord() End If End If End If End While End Module Copyright 2014 by Janson Industries Modifying Files 69 Module addRecord() Declare String custToAdd Declare String custNameInFile Declare String tempVariable Declare Boolean recordExists = false Modifying Files custToAdd = getCustomerName() Declare InputFile customerFile

Open customerFile "Customer.dat" While NOT eof(customerFile) AND recordExists = false Read customerFile custNameInFile If custNameInFile = custToAdd Then recordExists = true Else For ctr = 1 to 2 Read customerFile tempVariable End For End If End While Close customerFile Copyright 2014 by Janson Industries 70 Modifying Files If recordExists = true Then Display "Sorry there is already a record for customer " + custToAdd Else Declare OutputFile AppendMode customerFileOut Open customerFileOut "Customer.dat" Write customerFileOut custToAdd Display "What is the customers street address" Input tempVariable

Write customerFileOut tempVariable Display "What is the customers city, state and zip" Input tempVariable Write customerFileOut tempVariable Display "Customer " + custToAdd + " added" Close customerFileOut End If End Module 71 Copyright 2014 by Janson Industries Module modifyRecord() Declare String custToMod Declare String custNameInFile Declare String tempVariable Declare Boolean recordExists = false custToMod = getCustomerName() Declare OutputFile tempFile Open tempFile "TempFile.dat" Declare InputFile customerFile Open customerFile "Customer.dat" While NOT eof(customerFile) AND recordExists = false Read customerFile custNameInFile Write tempFile custNameInFile

Read till record If custNameInFile = custToMod Then to change recordExists = true found Else For ctr = 1 to 2 Read customerFile tempVariable Write tempFile tempVariable End For End If 72 End While Copyright 2014 by Janson Industries Modifying Files Modifying Files If record not found If recordExists = false Then Display "Sorry there is no record for customer " + custToMod Close customerFile Else Read customerFile tempVariable

Display "This is the customers current street address " Display tempVariable Display "What is the customers new street address" Input tempVariable If record found get new info and write it Write tempFile tempVariable to temFile Read customerFile tempVariable Display "This is the customers current city, state and zip" Display tempVariable Display "What is the customers new city, state and zip" Input tempVariable Write tempFile tempVariable Display "Customer " + custToMod + " changed" 73 End Copyright 2014Ifby Janson Industries Modifying Files While NOT eof(customerFile) Read customerFile tempVariable Write rest of customer records to

Write tempFile tempVariable tempFile End While Close customerFile Close tempFile Declare InputFile tempFileIn Open tempFileIn "TempFile.dat" Declare OutputFile customerFileOut Open customerFileOut "Customer.dat" While NOT eof(tempFileIn) Read tempFileIn tempVariable Write customerFileOut tempVariable End While Write all records to Close customerFileOut Customer from tempFile Close tempFileIn End Module 74 Copyright 2014 by Janson Industries Module displayRecord() Declare String custToDisp

Declare String custNameInFile Declare String tempVariable Declare Boolean recordExists = false custToDisp = getCustomerName() Declare InputFile customerFile Open customerFile "Customer.dat" While NOT eof(customerFile) AND recordExists = false Read customerFile custNameInFile Read till record If custNameInFile = custToDisp Then to display found recordExists = true Display custNameInFile When found For ctr = 1 to 2 display the 3 Read customerFile tempVariable records Display tempVariable End For Display " " End If End While Modifying Files

Copyright 2014 by Janson Industries 75 Modifying Files If recordExists = false Then Display "Sorry there is no customer " + custToDisp End If Close customerFile End Module Function String getCustomerName() String custName Display "What is the customers name" Input custName Return custName End Function Copyright 2014 by Janson Industries 76 Modifying Files Raptor

Raptor has a problem with accepting numeric characters as strings, will make option an Integer Can't append, so will have to work with temp file to do an Add Copyright 2014 by Janson Industries This means opening the TempFile when we open Customer As we search to see if customer already exists, write each record to temp 77 main method Modifying Files

Raptor Display options and input option Call correct function Copyright 2014 by Janson Industries 78 addRecord method Modifying Files Raptor Loop checking if customer already exists Copyright 2014 by Janson Industries 79

addRecord method Modifying Files Raptor Checking customer name No match: write name and next two records to the temp file Copyright 2014 by Janson Industries Close customer 80 file addRecord method Match:

display msg no add done Modifying Files Raptor No match: write name to temp prompt user to supply data, read, write to temp file Close temp, then open temp as input and customer as output Copyright 2014 by Janson Industries 81 addRecord method

Modifying Files Raptor Write all records from temp to customer Close files and display user msg Copyright 2014 by Janson Industries 82 Modifying Files Raptor In Raptor, when you are writing to a file, can't display info in console

So in modifyRecord: Copyright 2014 by Janson Industries Well you could but this means the redirect must be set to false and the next write will overwrite the file Won't prompt with current data Must get all the new data before redirecting Will need two more variables to hold the data 83 Modifying Files Raptor Alternatively, we could:

Copyright 2014 by Janson Industries Read the entire file looking for record Retrieve the data Then read the entire file again and write to the temp file, etc. Would mean a extra read of the entire file 84 modifyRecor d method //Declare variables String newAddr String newCSZ

Start recordExists false Modifying Files getCustomerName custToMod custName "What is the customers new street address"GET newAddr "What is the customers new city, state and zip"GET newCSZ Get new info Redirect_Input("E: / Customer.dat") Redirect_Output("E: / TempFile.dat") Set up files Loop

End_Of_Input OR recordExists = true Yes Copyright 2014 by Janson Industries No Loop to find record to be changed 85 No ""GET custNameInFile modifyRecor d method custNameInFile = custToMod Yes

recordExists true No PUT custNameInFile ctr 1 Loop Yes Check if record found Modifying Files Raptor ctr > 2 No ""GET tempVariable

PUT tempVariable No match: write cust name and next two records to temp ctr ctr + 1 Copyright 2014 by Janson Industries 86 recordExists =false Yes No Redirect_Input(false) PUT custToMod Redirect_Output(false)

PUT newAddr record for customer " + custToMod PUT newCSZ Modifying Files Raptor Match: write new customer data ""GET tempVariable No match: no change ""GET tempVariable Match: skip rest of old customer data

Loop Yes End_Of_Input No ""GET tempVariable PUT tempVariable Copyright 2014 by Janson Industries Match: write rest of data from customer to temp 87 Redirect_Input(false) Close files modifyRecor

d method Redirect_Output(false) Redirect_Output("E: / Customer.dat") Re-open so temp is input and customer is Redirect_Input("E: / TempFile.dat") output Modifying Files Raptor Loop Yes End_Of_Input No ""GET tempVariable Write all data from

temp to customer PUT tempVariable Copyright 2014 by Janson Industries 88 modifyRecor d method Modifying Files Raptor PUT tempVariable Redirect_Input(false) Close files Redirect_Output(false) PUT "Customer " + custToMod + " changed" Display user msg

End Copyright 2014 by Janson Industries 89 displayRecor d method Displaying Files Raptor Start recordExists false getCustomerName custToDisp custName Redirect_Input("E: / Customer.dat") Loop

End_Of_Input OR recordExists = true Yes Loop to search for record to display No ""GET custNameInFile custNameInFile = custToDisp Yes Copyright 2014 by Janson Industries No 90 recordExists true PUT custNameInFile

If record found display the name ctr 1 Displaying Files Raptor displayRecor d method Loop Yes ctr > 2 No ""GET tempVariable PUT tempVariable get and

display next 2 records with rest of data ctr ctr + 1 Copyright 2014 by Janson Industries 91 ctr ctr + 1 displayRecor d method PUT " " Displaying Files Raptor Display blank line recordExists = false Yes

If record was not found display user msg PUT "Sorry there is no customer " + custToDisp Redirect_Input(false) End Copyright 2014 by Janson Industries No Close file 92 Modifying Files Raptor getCustomerNa me method Start "What is the customers name"GET custName

End Copyright 2014 by Janson Industries 93 Modifying Files - Raptor Given this data Copyright 2014 by Janson Industries 94 Modifying Files Raptor Copyright 2014 by Janson Industries Running the flowchart results in: 95

Modifying Files Raptor Copyright 2014 by Janson Industries Specifying new customer info: 96 Modifying Files Raptor Changing customer info: Copyright 2014 by Janson Industries 97 Modifying Files Raptor Copyright 2014 by Janson Industries 98 Modifying Files Raptor

And this is the data at the end Copyright 2014 by Janson Industries 99 Modifying Files Java To write to a file you use a PrintWriter Specify the file name and location when creating the PrintWriter object Like you did with the Scanner PrintWriter tempFile = null; tempFile = new PrintWriter("E:/TempFile.dat");

Copyright 2014 by Janson Industries Have to enclose in try/catch or specify throws IOException in method header 100 Modifying Files Java To append to a file you also use a FileWriter But you create a FileWriter object and specify the file name and the value true PrintWriter customerFileOut = null; customerFileOut = new PrintWriter(new FileWriter("E:/Customer.dat", true)); Copyright 2014 by Janson Industries

101 Modifying Files Java To write you use the PrintWriters print or println methods customerFileOut.println("Frank Smith"); String custName = "Joe Blow" customerFileOut.print(custName); Copyright 2014 by Janson Industries println writes data to a new line in the file print writes to the same line Frank SmithJoe Blow

102 Modifying Files in Java import import import import import import java.io.File; java.io.FileNotFoundException; java.io.FileWriter; java.io.IOException; java.io.PrintWriter; java.util.Scanner; public class FileMod { static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { main method String option = ""; // Display menu of options while (!option.equals("4")) { System.out.println("What would you like to do? Enter:");

System.out.println("1 to add a customer"); System.out.println("2 to modify a customer"); System.out.println("3 to display a customer"); to end the pgm"); Copyright 2014 by System.out.println("4 Janson Industries 103 // Invoke correct method based on option selected if (option.equals("1")) { addRecord(); } else { if (option.equals("2")) { modifyRecord(); } else { if (option.equals("3")) { displayRecord(); } } } } Modifying Files in Java

} public static void addRecord() { addRecord // Variables to hold file data method String custToAdd, custNameInFile, tempVariable; boolean recordExists = false; // Variables for reading and writing to the customer file Scanner customerFile Copyright 2014 by Janson Industries = null; 104 // Retrieve the customer name to add custToAdd = getCustomerName(); // Create the scanner object to read the customer file try { customerFile = new Scanner(new File("E:/Customer.dat")); } catch (FileNotFoundException e) {

e.printStackTrace(); } // Read every record and compare every third record //with the new name while (customerFile.hasNext() && recordExists == false) { custNameInFile = customerFile.nextLine(); if (custNameInFile.equals(custToAdd)) { recordExists = true; } else { for (int ctr = 1; ctr < 3; ctr++) { tempVariable = customerFile.nextLine(); } Copyright 2014 by } Janson Industries Modifying Files in Java 105 // If customer name is already in file, don't add if (recordExists == true) { System.out.println("Sorry there is already a record for customer " + custToAdd); } else { // Create PrintWriter object to append to customer

file try { customerFileOut = new PrintWriter(new FileWriter( "E:/Customer.dat", true)); } catch (IOException e) { e.printStackTrace();} // Append the new name, address and CSZ to the customer file customerFileOut.println(custToAdd); System.out.println("What is the customers street address"); tempVariable = keyboard.nextLine(); customerFileOut.println(tempVariable); System.out.println("What is the customers city, state and zip"); tempVariable = keyboard.nextLine(); 106 End of addRecord Copyright 2014 by customerFileOut.println(tempVariable); Janson Industries public static void modifyRecord() { String custToMod, custNameInFile, tempVariable; boolean recordExists = false; modifyRecord

custToMod = getCustomerName(); method // Variables and objects for reading and writing // to the customer and temp files Scanner tempFileIn = null; Scanner customerFile = null; PrintWriter tempFile = null; PrintWriter customerFileOut = null; try { customerFile = new Scanner(new File("E:/Customer.dat")); tempFile = new PrintWriter("E:/TempFile.dat"); } catch (FileNotFoundException e) { e.printStackTrace(); } // Read the customer file and write the info to the temp // file until the customer to modify is found while (customerFile.hasNext() && recordExists == false) { custNameInFile = customerFile.nextLine(); 107 tempFile.println(custNameInFile); Copyright 2014 by Janson Industries

} else { for (int ctr = 1; ctr < 3; ctr++) { tempVariable = customerFile.nextLine(); tempFile.println(tempVariable); } } modifyRecord } method // If the customer name not in file, don't allow change if (recordExists == false) { System.out.println("Sorry there is no record for customer " + custToMod); customerFile.close(); } else { // Get the current customer info and display it // Read the new info and write it to the temp file tempVariable = customerFile.nextLine(); System.out.println("This is the customers current street address "); System.out.println(tempVariable); System.out.println("What is the customers new street address ");

tempVariable = keyboard.nextLine(); 108 tempFile.println(tempVariable); Copyright 2014 by Janson Industries tempVariable = customerFile.nextLine(); System.out.println("This is the customers current city, state and zip "); System.out.println(tempVariable); System.out.println("What is the customers new city, state and zip "); tempVariable = keyboard.nextLine(); tempFile.println(tempVariable); System.out.println("Customer " + custToMod + " changed"); // Write the rest of the customer records to the temp file while (customerFile.hasNext()) { tempVariable = customerFile.nextLine(); tempFile.println(tempVariable); } // Close the files then create new objects to modifyRecord // read the temp file and write

to the customer file method customerFile.close(); tempFile.close(); try { tempFileIn = new Scanner(new 109 File("E:/TempFile.dat")); Copyright 2014 by Janson Industries // Copy all the temp file records to the customer file while (tempFileIn.hasNext()) { tempVariable = tempFileIn.nextLine(); customerFileOut.println(tempVariable); End modifyRecord } customerFileOut.close(); method tempFileIn.close(); } } // Display a particular customers record. displayRecord

// Uses same logic as FileLoop. method public static void displayRecord() { String custToDisp, custNameInFile, tempVariable; boolean recordExists = false; Scanner customerFile = null; custToDisp = getCustomerName(); try { customerFile = new Scanner(new File("E:/Customer.dat")); Copyright 2014 by Janson Industries 110 while (customerFile.hasNext() && recordExists == false) { custNameInFile = customerFile.nextLine(); if (custNameInFile.equals(custToDisp)) { recordExists = true; System.out.println(custNameInFile); for (int ctr = 1; ctr < 3; ctr++) { tempVariable = customerFile.nextLine(); System.out.println(tempVariable); } System.out.println("");

} } if (recordExists == false) { System.out.println("Sorry there is no customer " + custToDisp); } End displayRecord method customerFile.close(); } public static String getCustomerName() { String custName; System.out.println("What is the customers name"); custName = keyboard.nextLine(); getCustomerName return custName; method } 2014 by Janson Industries Copyright 111 Modifying Files - Java Given this data Copyright 2014 by Janson Industries

112 Modifying Files - Java Choose add Add new customer Display newly added customer info Copyright 2014 by Janson Industries 113 Modifying Files - Java Choose modify Change some of the data Display changed

customer info Copyright 2014 by Janson Industries 114 Modifying Files - Java Test that all checks work Try to add an already existing customer Try to change and display a non-existing customer Copyright 2014 by Janson Industries 115 Modifying Files - Java

And this is the data at the end Copyright 2014 by Janson Industries 116 Processing File Data Files can hold both text and numbers Instead of using parallel arrays can use files to hold different types of info 117 Copyright 2014 by Janson Industries Processing Data And a language like Java lets you

read individual values not just the whole record next() gets all text up to the next space nextInt() gets all text up to the next space and converts it to an integer nextDouble() gets all text up to the next space and converts it to a double All of these do not advance the cursor to the next line! 118 Copyright 2014 by Janson Industries Processing Data

Not nitpicking! If file had the following budget data Rent 500 Car 280 Utilities 175 And you tried to process with these statements While (not eof) name = infile.nextLine() amount = infile.nextDouble() End While Copyright 2014 by Janson Industries 119 Processing Data

There would be an exception the second time nextDouble executed WHAAAAAAAT!! Must show where cursor is after each statement executed to understand First nextLine() reads "Rent" and places cursor at the beginning of the second line in the file 120 Copyright 2014 by Janson Industries Processing Data When nextDouble executed 500 read and cursor placed at end after

the second 0 Rent 500 Car 280 Utilities 175 Cursor after first read Cursor after second read When the second nextLine executed it reads the rest of the second line A big fat null 121 Copyright 2014 by Janson Industries

Processing Data And moves cursor to beginning of third line Cursor after 3rd read (2nd nextLine) Rent 500 Car 280 Utilities 175 Now when second nextDouble executed InputMismatchException

Tries to convert "Car" into a double 122 Copyright 2014 by Janson Industries Processing Data Solution: Execute another nextLine after the nextDouble Forces the cursor to the line after the line with the double value While (not eof) name = infile.nextLine() amount = infile.nextDouble() infile.nextLine() End While

123 Copyright 2014 by Janson Industries Processing Data When using files like this, there is generally a file specification document which Identifies each field of data with a Name Location within the file Size (optional) Data type 124 Copyright 2014 by Janson Industries

Processing Data So we could have stored the customer data like this The file specification would look something like this 125 Copyright 2014 by Janson Industries Processing Data File Name: customer.dat Description: contains the name and address of each customer Field Description Data Type Customer first name String Customer last name String

Street number String Street name String Street type String City String State String Zip code String 126 Copyright 2014 by Janson Industries Processing Data Storing data this way could cause problems What if street name is comprised of multiple words

23 Pond View Dr. 14 Puppy Dog Tr. 2300 Martin Luther King Hwy How do you know how many reads to do? Could add a new field that has the street name length (number of words) 127 Copyright 2014 by Janson Industries Processing Data Joe Customer 1 1 Main St Enid, OK 34343 Mary Buyer 2 1 Oak St. Muncie, IN 54545 Terry Smith 3 1 Pine Ave. Palatka, FL 32273 Pat Jones 4 1 Lake Dr. Erie, PA

23232 Frank Smith 5 1 Minerva La Ronkonkoma, NY 11783 Joe Blow 23 2 Pond View Dr. Santa Barbara, CA 99999 Sue Banks 14 2 Puppy Dog Tr. Walla Walla, WA 97654 Al Adams 2300 3 Martin Luther King Hwy El Paso, NM 83536 Uh-oh what about city now? This is why text files are of limited use and DBMS are so important 128 Copyright 2014 by Janson Industries Processing Data Control breaks are interuptions in normal program execution Like when a record was modified

Normal processing was copying the data from the customer file to the temp file When the customer to change was reached, different instructions were performed The new info was retrieved from the user and written to the temp file Then the copying continued Control breaks used frequently when printing reports 129 Copyright 2014 by Janson Industries Control Breaks

Example, a report that has the following format: Report header (on first page) For each subsequent page A page header with page number For next 33 items Print line item (from file data) A page footer with page number Report footer (on last page) 130

Copyright 2009 by Janson Industries Control Breaks Wisconsin State Sales Report xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx : : : : xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx

xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx : : : : xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx

xxxxxxx : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx Detailed Wisconsin Sales Report page 2 xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : :

: : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx : : : : xxxx

xxxx xxxx xxxx xxxx xxxx xxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx : : : : xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx

xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxx xxxxx xxxxx xxxxx xxxxx

xxxxx xxxxx : : : : : : : : xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx

xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx : : : : xxxxx xxxxx xxxxx xxxxx xxxxx

xxxxx xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx : : : : : : : : xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx

End of page 2 Copyright 2009 by Janson Industries xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx

xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx :

: : : xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx

xxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx 131 Control Breaks Detailed Wisconsin Sales Report page 3 xxxxx xxxxx xxxxx

xxxxx xxxxx xxxxx xxxxx : : : : xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx : :

: : xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx

xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : : : : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx

xxxxxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx : : : : xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx

xxxxxxxxx xxxxxxxxx xxxxxxxxx : : : : xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : :

: xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx : : : : : : : : xxxxx

xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx

xxxxx xxxxx xxxxx xxxxx xxxxx : : : : xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx :

: : : : : : : xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : :

: xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx : : : : xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx

xxxxxxx xxxxxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx : : : : xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx

xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxxxx xxxxxxx xxxxxxx xxxxxxx xxxxxxx

xxxxxxx xxxxxxx xxxxxxx End of page 3 End of Wisconsin State Sales Report 132 Copyright 2009 by Janson Industries Control Breaks Module main() Declare Integer pageCtr = 1, lineCtr = 0 Declare String reportHeader = "Wisconsin State Sales Report " Declare String pageHeader = " Detailed Wisconsin Sales Report page " Declare String pageFooter = " End of page " Declare String reportFooter = " End of Wisconsin State Sales Report" Display reportHeader Skip to next page pageCtr = pageCtr + 1 // Declare and open the file

Declare InputFile salesFile Open salesFile "sales.dat" // Priming read Read salesFile tempVariable 133 Copyright 2009 by Janson Industries Use Nested Loops Outer Loop While (not eof) Display pageHeader, pageCtr While (lineCtr < 33 AND not eof) Display tempVariable Inner lineCtr = lineCtr + 1 Loop Read salesFile tempVariable End While lineCtr = 0 Display pageFooter, pageCtr Skip to next page pageCtr = pageCtr + 1

End While Display reportFooter End Module Copyright 2009 by Janson Industries 134 Points to Remember Files can hold many values of differing types Hold data permanently Progam ends but data is still in the file Just as with arrays, easiest to process files with loops

135 Copyright 2014 by Janson Industries Assignments Non-Graded Chap 9 labs 9.1-9.3 Graded Chap 9 lab 9.4 136 Copyright 2014 by Janson Industries

Recently Viewed Presentations

  • The Course of war 1914-1918

    The Course of war 1914-1918

    The February (March) Revolutions: 1917. Workers, women go on strike. Demand food and fuel. Soldiers left front lines to deal with issue, instead joined in. Led to uprising throughout Russia
  • Equella Interface changes and new functionality

    Equella Interface changes and new functionality

    Login Equella. leocontent.acu.edu.au. Get lecturers to create 2 Words docs and PDF 'to print' in 1 folder. Get them to create another folder and create 3 Docs. They will be uploading the content of the 1st folder via LEO, and...
  • Diapositiva 1 - The E-3 Healy Zone

    Diapositiva 1 - The E-3 Healy Zone

    PRESENTING OUR POEMS Scansion The Rules of Poetic Rhythm and Meter Rhythm: Any wavelike recurrence of motion or speech Stress Syllable toDAY, toMORrow, YESterday Rhetorical stress Pause Punctuation Comma, period, semi-colon, colon, dash Line endings End stopped line Line ends...
  • The Role of the Speech-Language Pathologist in the Assessment ...

    The Role of the Speech-Language Pathologist in the Assessment ...

    The Role of the Speech-Language Pathologist in the Assessment &Treatment of TBI . Cassaundra N. Miller, MS, CCC/SLP. West Virginia University Center for Excellence in Disabilities
  • Public Goods and Common Resources - University of Arizona

    Public Goods and Common Resources - University of Arizona

    A road is which of the four kinds of goods? Hint: The answer depends on whether the road is congested or not, and whether it's a toll road or not. Consider the different cases. Categorizing roads. This brief exercise gives...
  • Unit: The Era of Jackson MYP Unit Question:

    Unit: The Era of Jackson MYP Unit Question:

    Was it really a "Corrupt Bargain"? Monday: What compromise combined the Virginia and New Jersey Plans to create the two houses of Congress? Was the election of 1824 rigged? John Quincy Adams, Andrew Jackson, Henry Clay. 2. No one had...
  • Professionalism in the Workplace PROFESSIONAL DEVELOPMENT TRAINING AMANDA

    Professionalism in the Workplace PROFESSIONAL DEVELOPMENT TRAINING AMANDA

    Professionalism by the Books. Professionalism Defined. the conduct or qualities that characterize or mark an individual holding an occupation . the skill level, of course, but also good judgment and polite behavior that is expected from a person who is...
  • Forensic psychology

    Forensic psychology

    Psychodynamic - gender bias or psychic determinism. Issues and debates. This task will get you thinking about how to use the issues and debates to evaluate each of the explanations for offending behaviour. It is also designed to get you...