Download presentation
Presentation is loading. Please wait.
1
Intro to Programming & Algorithm Design
4/20/2018 Intro to Programming & Algorithm Design Data Files Assg This presentation can be viewed on line in a file named: ch09.IntrotoProg.Files.ppt Copyright 2003 by Janson Industries
2
Objectives Explain Show how to use files in Java Advantages of files
4/20/2018 Objectives Explain Advantages of files How to process files Show how to use files in Java
3
File Everything on a computer is stored in files Images Documents
4/20/2018 File Everything on a computer is stored in files Images Documents Web pages Spreadsheet Flowcharts Java source code Java bytecode
4
Data File We are talking about data files
4/20/2018 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
5
4/20/2018 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
6
Data Files Are stored on secondary storage
4/20/2018 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)
7
4/20/2018 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
8
4/20/2018 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 Actually closing forces any data still in the buffer into the file.
9
Files In pseudocode you must declare a program file name
4/20/2018 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
10
Files Windows file's physical names have a prefix and a suffix
4/20/2018 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
11
Writing to Files Declare the file as an output file
4/20/2018 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 " Close customerFile
12
Results in the 3 variables holding the file data
4/20/2018 Reading Files Declare the program file name as input Associate it with the physical file name Read the file Declare String custName, custStreet, custCSZ Declare InputFile customerFile Open customerFile "Customer.dat" Read customerFile custName Read customerFile custStreet Read customerFile custCSZ Close customerFile Results in the 3 variables holding the file data
13
Appending to Files In the declare, identify the mode as AppendMode
4/20/2018 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
14
Using Loops to Process Files
4/20/2018 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
15
Using Loops to Process Files
4/20/2018 Using Loops to Process Files 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
16
Using Loops to Process Files
4/20/2018 Using Loops to Process Files Assuming Customer.dat has the following info
17
Using Loops to Process Files
4/20/2018 Using Loops to Process Files To display a mailing list like this: Joe Customer 1 Main St. Enid, OK Mary Buyer 2 Oak St. Muncie, IN 54545 Terry Smith 3 Pine Ave. Palatka, FL 32273 Pat Jones 4 Lake Dr. Erie, PA
18
Using Loops to Process Files
4/20/2018 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 End Module
19
Raptor Flowgorithm cannot process files So new tool - Raptor
4/20/2018 Raptor Flowgorithm cannot process files So new tool - Raptor Like Flowgorithm, can execute the flowchart Several differences between Flowgorithm and Raptor
20
Raptor No declare function Only global variables
4/20/2018 Raptor No declare function Must specify Declares as commments Only global variables No passing variables between modules No distinction between modules and functions Input function also has output function for prompt text
21
4/20/2018 Raptor For example, here’s a Raptor FC that adds two numbers
22
4/20/2018 Raptor When executed result is:
24
Scroll down
25
Click drop down button, select Save As, then specify your thumb drive
Click Save
26
Double click to start install
29
Specify thumb drive location (this way you can run from any computer)
32
To run, double click raptor.exe
33
Or from the All Apps menu, select Raptor
34
This is where the flowchart is defined
Output shown here
35
To add a symbol, click to select…
Raptor To add a symbol, click to select…
36
… then click in flowchart where to put the symbol
Raptor … then click in flowchart where to put the symbol You can also drag/drop
37
To edit symbol (add function) click symbol…
Raptor To edit symbol (add function) click symbol…
38
Then click Edit and Edit Selection
Raptor Then click Edit and Edit Selection
39
Enter statement(s), click done
Raptor Enter statement(s), click done
40
To run, click the Execute to Completion button
Raptor To run, click the Execute to Completion button
41
Output displayed in Console
Raptor Output displayed in Console
42
Raptor Raptor has two symbols for I/O
4/20/2018 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
43
Can also just double click the symbol to edit
Raptor Can also just double click the symbol to edit
44
Enter prompt text, variable to hold info, click Done
Raptor Enter prompt text, variable to hold info, click Done
45
Notice Raptor uses + not & to concatenate
Added an output symbol Notice Raptor uses + not & to concatenate
46
As each symbol is executed, it’s outlined in green
Raptor As each symbol is executed, it’s outlined in green
47
Raptor When input symbol reached, program execution halts and a window is displayed with the prompt text and an input field
48
User should enter the input and click OK
Raptor User should enter the input and click OK
49
Raptor Program finishes executing and results displayed in console
To insert a comment, right click a symbol and select Comment
50
4/20/2018 Files in Raptor To read, use the Input function but must first identify the file as the source of the input I.e. not the keyboard/console Done by calling the Redirect_Input function Redirect_Input("E:/Customer.dat") To write to a file use the Redirect_Output function
51
Using File Loops in Raptor
4/20/2018 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 Redirect_Input(false)
52
Using File Loops in Raptor
4/20/2018 Using File Loops in Raptor EOF loop to read all records Loop to read the three records for each customer
53
Using File Loops in Raptor
4/20/2018 Reads and displays a record Blank line separating each customers data Close the file
54
Using File Loops in Raptor
4/20/2018 Using File Loops in Raptor Results
55
4/20/2018 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"));
56
4/20/2018 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 {
57
Files in Java Or you can enclose the statement as follows
4/20/2018 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(); }
58
Using File Loops in Java
4/20/2018 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();
59
Using File Loops in Java
import java.io.File; import java.io.IOException; import java.util.Scanner; public class FileLoop { 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 customerFile.close(); } } 4/20/2018 Using File Loops in Java
60
Using File Loops in Java
4/20/2018 Using File Loops in Java
61
Modifying Files Text files not always easy to add to or modify
4/20/2018 Modifying Files Text files not always easy to add to or modify 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
62
Modifying Files To add when language doesn't allow adding, have to:
4/20/2018 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 I.e. write over what was in the original file
63
Modifying Files - Adding
4/20/2018 Modifying Files - Adding Old Data Old Data Customer.dat AddPgm TempFile.dat New Data New Data AddPgm User Old and New Data Old and New Data AddPgm
64
4/20/2018 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
65
Modifying a Record User specifies record to modify
4/20/2018 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 Read rest of original records and write them to temp Copy temp back to original
66
Modifying a Record Data To Modify AddPgm User Data Records Up to the
one to modify Data Records Up to the one to modify Customer.dat AddPgm TempFile.dat Old Data New Data AddPgm User New Data
67
Modifying a Record Rest of Data Rest of Data Customer.dat AddPgm
TempFile.dat All Data All Data Customer.dat AddPgm TempFile.dat
68
4/20/2018 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 If info does exist, will not allow user to add
69
Modifying Files 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 While End Module Modifying Files 4/20/2018
70
Modifying Files Module addRecord() Declare String custToAdd
Declare String custNameInFile Declare String tempVariable Declare Boolean recordExists = false 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 Modifying Files 4/20/2018
71
Modifying Files If recordExists = true Then
4/20/2018 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" Display "Customer " + custToAdd + " added" Close customerFileOut End If End Module
72
Read till record to change found
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 If custNameInFile = custToMod Then recordExists = true Else For ctr = 1 to 2 Read customerFile tempVariable Write tempFile tempVariable End For End If End While 4/20/2018 Modifying Files Read till record to change found
73
If record found get new info and write it to temFile
Modifying Files 4/20/2018 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 Write tempFile tempVariable Display "This is the customers current city, state and zip" Display "What is the customers new city, state and zip" Display "Customer " + custToMod + " changed" End If If record found get new info and write it to temFile
74
Modifying Files While NOT eof(customerFile)
4/20/2018 While NOT eof(customerFile) Read customerFile tempVariable Write tempFile tempVariable 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 Close customerFileOut Close tempFileIn End Module Write rest of customer records to tempFile Write all records to Customer from tempFile
75
Read till record to display found When found display the 3 records
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 If custNameInFile = custToDisp Then recordExists = true Display custNameInFile For ctr = 1 to 2 Read customerFile tempVariable Display tempVariable End For Display " " End If End While 4/20/2018 Modifying Files Read till record to display found When found display the 3 records
76
Modifying Files If recordExists = false Then
4/20/2018 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
77
Modifying Files Raptor
4/20/2018 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 This means opening the TempFile when we open Customer As we search to see if customer already exists, write each record to temp
78
Modifying Files Raptor
4/20/2018 main method Modifying Files Raptor Display options and input option Call correct function
79
Modifying Files Raptor
addRecord method 4/20/2018 Modifying Files Raptor Loop checking if customer already exists
80
Modifying Files Raptor
addRecord method 4/20/2018 Modifying Files Raptor Checking customer name No match: write name and next two records to the temp file Close customer file
81
Modifying Files Raptor
addRecord method 4/20/2018 Modifying Files Raptor No match: write name to temp prompt user to supply data, read, write to temp file Match: display msg no add done Close temp, then open temp as input and customer as output
82
Modifying Files Raptor
4/20/2018 addRecord method Modifying Files Raptor Write all records from temp to customer Close files and display user msg
83
Modifying Files Raptor
4/20/2018 Modifying Files Raptor In Raptor, when you are writing to a file, can't display info in console Well… you could but this means the redirect must be set to false and the next write will overwrite the file So in modifyRecord: Won't prompt with current data Must get all the new data before redirecting Will need two more variables to hold the data
84
Modifying Files Raptor
4/20/2018 Modifying Files Raptor Alternatively, we could: 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…
85
Loop to find record to be changed
modifyRecord method 4/20/2018 Modifying Files Get new info Set up files Loop to find record to be changed
86
Modifying Files Raptor
4/20/2018 modifyRecord method Check if record found Modifying Files Raptor No match: write cust name and next two records to temp
87
Modifying Files Raptor
4/20/2018 Modifying Files Raptor Match: write new customer data Match: skip rest of old customer data No match: no change Match: write rest of data from customer to temp 87
88
Modifying Files Raptor
4/20/2018 modifyRecord method Close files Modifying Files Raptor Re-open so temp is input and customer is output Write all data from temp to customer
89
Modifying Files Raptor
4/20/2018 modifyRecord method Modifying Files Raptor Close files Display user msg
90
Displaying Files Raptor
4/20/2018 displayRecord method Displaying Files Raptor Loop to search for record to display
91
Displaying Files Raptor
4/20/2018 If record found display the name… Displaying Files Raptor displayRecord method …get and display next 2 records with rest of data
92
Displaying Files Raptor
displayRecord method 4/20/2018 Displaying Files Raptor Display blank line If record was not found display user msg Close file
93
Modifying Files Raptor
4/20/2018 Modifying Files Raptor getCustomerName method
94
Modifying Files - Raptor
4/20/2018 Modifying Files - Raptor Given this data
95
Modifying Files Raptor
4/20/2018 Modifying Files Raptor Running the flowchart results in:
96
Modifying Files Raptor
4/20/2018 Modifying Files Raptor Specifying new customer info:
97
Modifying Files Raptor
4/20/2018 Modifying Files Raptor Changing customer info:
98
Modifying Files Raptor
4/20/2018 Modifying Files Raptor
99
Modifying Files Raptor
4/20/2018 Modifying Files Raptor And this is the data at the end
100
Modifying Files Java To write to a file you use a PrintWriter
4/20/2018 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 Have to enclose in try/catch or specify throws IOException in method header PrintWriter tempFile = null; tempFile = new PrintWriter("E:/TempFile.dat");
101
Modifying Files Java To append to a file you also use a FileWriter
4/20/2018 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));
102
4/20/2018 Modifying Files Java To write you use the PrintWriters print or println methods println writes data to a new line in the file print writes to the same line customerFileOut.println("Frank Smith"); String custName = "Joe Blow" customerFileOut.print(custName); Frank SmithJoe Blow
103
Modifying Files in Java
4/20/2018 import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class FileMod { static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { 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"); System.out.println("4 to end the pgm"); option = keyboard.nextLine(); main method
104
Modifying Files in Java
4/20/2018 // Invoke correct method based on option selected if (option.equals("1")) { addRecord(); } else { if (option.equals("2")) { modifyRecord(); if (option.equals("3")) { displayRecord(); } public static void addRecord() { // Variables to hold file data String custToAdd, custNameInFile, tempVariable; boolean recordExists = false; // Variables for reading and writing to the customer file Scanner customerFile = null; PrintWriter customerFileOut = null; Modifying Files in Java addRecord method
105
Modifying Files in Java
// 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(); customerFile.close(); 4/20/2018 Modifying Files in Java
106
End of addRecord method
// 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"); System.out.println("Customer " + custToAdd + " added"); customerFileOut.close(); } 4/20/2018 End of addRecord method
107
modifyRecord method public static void modifyRecord() {
String custToMod, custNameInFile, tempVariable; boolean recordExists = false; custToMod = getCustomerName(); // 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(); tempFile.println(custNameInFile); if (custNameInFile.equals(custToMod)) { recordExists = true; 4/20/2018 modifyRecord method
108
modifyRecord method } else { for (int ctr = 1; ctr < 3; ctr++) {
tempVariable = customerFile.nextLine(); tempFile.println(tempVariable); } // 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(); // Get the current customer info and display it // Read the new info and write it to the temp file 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(); 4/20/2018 modifyRecord method
109
modifyRecord method 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()) { } // Close the files then create new objects to // read the temp file and write to the customer file customerFile.close(); tempFile.close(); try { tempFileIn = new Scanner(new File("E:/TempFile.dat")); customerFileOut = new PrintWriter("E:/Customer.dat"); } catch (FileNotFoundException e) { e.printStackTrace();} 4/20/2018 modifyRecord method
110
End modifyRecord method
// Copy all the temp file records to the customer file while (tempFileIn.hasNext()) { tempVariable = tempFileIn.nextLine(); customerFileOut.println(tempVariable); } customerFileOut.close(); tempFileIn.close(); // Display a particular customers record. // Uses same logic as FileLoop. 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")); } catch (FileNotFoundException e) { e.printStackTrace(); } 4/20/2018 End modifyRecord method displayRecord method
111
End displayRecord method getCustomerName method
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); } customerFile.close(); public static String getCustomerName() { String custName; System.out.println("What is the customers name"); custName = keyboard.nextLine(); return custName; 4/20/2018 End displayRecord method getCustomerName method
112
4/20/2018 Modifying Files - Java Given this data
113
Display newly added customer info
4/20/2018 Modifying Files - Java Choose add Add new customer Display newly added customer info
114
Display changed customer info
4/20/2018 Modifying Files - Java Choose modify Change some of the data Display changed customer info
115
Modifying Files - Java Test that all checks work
4/20/2018 Modifying Files - Java Test that all checks work Try to add an already existing customer Try to change and display a non-existing customer
116
4/20/2018 Modifying Files - Java And this is the data at the end
117
Processing File Data Files can hold both text and numbers
4/20/2018 Processing File Data Files can hold both text and numbers Instead of using parallel arrays can use files to hold different types of info
118
Processing Data 4/20/2018 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!
119
Processing Data Not nitpicking! If file had the following budget data
4/20/2018 Not nitpicking! If file had the following budget data And you tried to process with these statements Rent 500 Car 280 Utilities 175 While (not eof) name = infile.nextLine() amount = infile.nextDouble() End While
120
Processing Data 4/20/2018 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
121
Cursor after first read Cursor after second read
Processing Data 4/20/2018 When nextDouble executed 500 read and cursor placed at end after the second 0 When the second nextLine executed it reads the rest of the second line A big fat null Rent 500 Car 280 Utilities 175 Cursor after first read Cursor after second read
122
Processing Data And moves cursor to beginning of third line
4/20/2018 And moves cursor to beginning of third line Now when second nextDouble executed InputMismatchException Tries to convert "Car" into a double Rent 500 Car 280 Utilities 175 Cursor after 3rd read (2nd nextLine)
123
Processing Data Solution:
4/20/2018 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
124
4/20/2018 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
125
Processing Data So we could have stored the customer data like this
4/20/2018 Processing Data So we could have stored the customer data like this The file specification would look something like this…
126
Processing Data File Name: customer.dat
4/20/2018 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
127
Processing Data Storing data this way could cause problems
4/20/2018 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)
128
Processing Data Uh-oh what about city now?
4/20/2018 Processing Data Joe Customer 1 1 Main St Enid, OK 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 Frank Smith 5 1 Minerva La Ronkonkoma, NY Joe Blow 23 2 Pond View Dr. Santa Barbara, CA Sue Banks 14 2 Puppy Dog Tr. Walla Walla, WA 97654 Al Adams 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
129
4/20/2018 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
130
Control Breaks Example, a report that has the following format:
4/20/2018 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)
131
Detailed Wisconsin Sales Report – page 2
Control Breaks 4/20/2018 Wisconsin State Sales Report Detailed Wisconsin Sales Report – page 2 xxxxx xxxxxxxx xxxxxxx xxxxxxx xxxx xxxxxxxxx xxxxxxx xxxxx xxxxx xxxxx xxxxxxxx xxxxxxx xxxxxxx xxxx xxxxxxxxx xxxxxxx : : : : : : : : : : : : : : : : End of page 2
132
Detailed Wisconsin Sales Report – page 3
Control Breaks 4/20/2018 Detailed Wisconsin Sales Report – page 3 xxxxx xxxxxxxx xxxxxxx xxxxxxx xxxx xxxxxxxxx xxxxxxx xxxxx xxxxx xxxxx xxxxxxxx xxxxxxx xxxxxxx xxxx xxxxxxxxx xxxxxxx : : : : : : : : : : : : : : : : End of page 3 End of Wisconsin State Sales Report
133
Control Breaks Module main() Declare Integer pageCtr = 1, lineCtr = 0
4/20/2018 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
134
Use Nested Loops Inner Loop Outer Loop While (not eof)
4/20/2018 Use Nested Loops While (not eof) Display pageHeader, pageCtr While (lineCtr < 33 AND not eof) Display tempVariable lineCtr = lineCtr + 1 Read salesFile tempVariable End While lineCtr = 0 Display pageFooter, pageCtr Skip to next page pageCtr = pageCtr + 1 Display reportFooter End Module Inner Loop Outer Loop
135
Points to Remember Files can hold many values of differing types
4/20/2018 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
136
Assignments Non-Graded Graded Chap 9 labs 9.1-9.3 Chap 9 lab 9.4
4/20/2018 Assignments Non-Graded Chap 9 labs Graded Chap 9 lab 9.4
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.