1 / 84

Chapter 6 Using Classes: Dates and I/O Streams

Chapter 6 Using Classes: Dates and I/O Streams. Date, DateFormat, GregorianCalendar Classes Reading from Keyboard with Input Stream Using Streams to Read and Write Text Files Database Management Systems. Classes: Uses in Java. Package related group of methods

Download Presentation

Chapter 6 Using Classes: Dates and I/O Streams

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 6Using Classes: Dates and I/O Streams Date, DateFormat, GregorianCalendar Classes Reading from Keyboard with Input Stream Using Streams to Read and Write Text Files Database Management Systems

  2. Classes: Uses in Java • Package related group of methods • Example: Math class • Use methods with name of the class • int x = Math.abs(y); • Make a new data type • Example: Turtle class • Make an object of the class • Turtle myTurtle = new Turtle(); • Use methods with objects • myTurtle.move(100); Programming and Problem Solving With Java

  3. Classes: Why Use? • Make Java extensible • Can add new features to the language • Can build on existing features, or start from scratch • Example: String class • String not primitive in Java • Works almost like a primitive type • Many standard classes • Dates  User Interface  Exceptions • Files  Networking  Databases • Applets  Data storage  Electronic • Threads  Random numbers commerce Programming and Problem Solving With Java

  4. Classes: Why Use? • Classes form basis of program development • Given problem, Java programmer should • Look for classes appropriate to the problem domain • If there are no existing classes • Extend existing classes, or • Write new classes from scratch • Classes are essence of object-oriented programming Programming and Problem Solving With Java

  5. Date Classes: Date • Three of Java's many Dateclasses • Date • DateFormat • GregorianCalendar • The Date class • Date object represents a particular point in time • To create an object of the class • Date aDate = new Date(); • Date constructor initializes with today's date and time new operator makes object Constructor Programming and Problem Solving With Java

  6. Date Classes: DateFormat • Display Date object • Date aDate = new Date(); • System.out.println(aDate); • Mon Apr 20 16:49:32 CST 1998 • DateFormat: format Date object for display • DateFormat is abstract: can't create objects with new • To create a DateFormat object • DateFormat aDateFormatter = DateFormat.getDateInstance(); • Use format() method to format a Date object • Date aDate = new Date(); • DateFormat aDateFormatter = DateFormat.getDateInstance(); • String aString = aDateFormatter.format(aDate); • 20-Apr-1998 Programming and Problem Solving With Java

  7. Date Classes: DateFormat • Four date formats • Specify format in DateFormat.getDateInstance() • Date aDate = new Date(); • DateFormat aDateFormatter • = DateFormat.getDateInstance(DateFormat.FULL); • String aString = aDateFormatter.format(aDate); • Monday, April 20, 1998 • Can specify locale in DateFormat.getDateInstance() • DateFormat aDateFormatter • = DateFormat.getDateInstance(Locale.FRANCE); Programming and Problem Solving With Java

  8. Date Classes: GregorianCalendar • Use GregorianCalendar object to set day • // Example of GregorianCalendar class. This program initializes a • // GregorianCalendar object to October 15, 1999, converts the object • // to a Date object, then displays the result with DateFormat. • import java.util.GregorianCalendar; • import java.util.Calendar; • import java.text.DateFormat; • import java.util.Date; • class SetDate • { • public static void main(String[] args) • { • // Make a DateFormat object that formats in FULL style • DateFormat aDateFormatter • = DateFormat.getDateInstance(DateFormat.FULL); • // Initialize aGregCal to October 15, 1999 • GregorianCalendar aGregCal • = new GregorianCalendar(1999, Calendar.OCTOBER, 15); • // Convert aGregCal to aDate object • Date aDate = aGregCal.getTime(); • // Display the date with the formatter • System.out.println(aDateFormatter.format(aDate)); • } • } Programming and Problem Solving With Java

  9. Date Classes: Discarding Objects • Create new GregorianCalendar object, assign to variable • GregorianCalendar someDate • = new GregorianCalendar(1999, Calendar.MAY, 12); • Create another object, assign to same variable • someDate = new GregorianCalendar(1998, Calendar.APRIL, 20); • Garbage collection: Clean up discarded objects Programming and Problem Solving With Java

  10. Input Streams • Stream is flow of data • Reader at one end • Writer at the other end • Stream generalizes input & output • Keyboard electronics different from disk • Input stream makes keyboard look like a disk Stream Writer Reader Programming and Problem Solving With Java

  11. What's the Keyboard class hiding? The System..in stream! System.in Input Streams: Keyboard Class • Have been using Keyboard class for reading • int num = Keyboard.readInt("Enter number: "); Programming and Problem Solving With Java

  12. Input Streams: System.in • System.in: the standard input stream • By default, reads characters from the keyboard • Can use System.in many ways • Directly (low-level access) • Through layers of abstraction (high-level access) System.in Program Programming and Problem Solving With Java

  13. Input Streams: Read Characters • Can read characters from System.in with read() • // Reads a single character from the keyboard and displays it • class DemonstrateRead • { • public static void main(String[] args) • throws java.io.IOException • { • char character; • // Prompt for a character and read it • System.out.print("Enter a character: "); • System.out.flush(); • character = (char) System.in.read(); • // Display the character typed • System.out.println(); • System.out.println("You typed " + character); • } • } Programming and Problem Solving With Java

  14. Input Streams: Read Characters • System.in.read() returns an integer • Usually cast to char • char character = (char) System.in.read(); • System.in.read returns -1 if EOF detected • EOF = end of file (no more characters in stream) • Signaling EOF at keyboard • Control-Z (Windows), Control-D (Unix) • Example: Read all characters in stream until EOF • int intChar = System.in.read(); • while (intChar != -1) • { • // Convert to character • char character = (char) intChar; • System.out.println("Next character is " + character); • // Get next one • intChar = System.in.read(); • } Programming and Problem Solving With Java

  15. Input Streams: Read Characters • Example: Count digits, letters, other characters • Part 1: Setup • // Reads text from the keyboard and displays the • // number of digits, upper case letters, lower case letters, • // and other characters that the user typed. • class CountCharacters • { • public static void main(String[] args) • throws java.io.IOException • { • int nextValue, numUpperCase = 0, numLowerCase = 0, • numDigits = 0, numOther = 0; • char nextChar; • // Display instructions • System.out.println("Enter some text, terminate with EOF"); Programming and Problem Solving With Java

  16. Input Streams: Read Characters • Part 2: Read and count • // Read from the input stream, count characters until no more • // characters in the input stream • nextValue = System.in.read(); • while (nextValue != -1) • { • nextChar = (char) nextValue; • if (Character.isDigit(nextChar)) • { • numDigits++; • } • else if (Character.isUpperCase(nextChar)) • { • numUpperCase++; • } • else if (Character.isLowerCase(nextChar)) • { • numLowerCase++; • } • else • { • numOther++; • } • nextValue = System.in.read(); • } Programming and Problem Solving With Java

  17. Input Streams: Read Characters • Part 3: Display results • // Display results • System.out.println(); • System.out.println(); • System.out.println("Number of digits: " • + numDigits); • System.out.println("Number of upper case letters: " • + numUpperCase); • System.out.println("Number of lower case letters: " • + numLowerCase); • System.out.println("Number of other characters: " • + numOther); • } • } Programming and Problem Solving With Java

  18. Input Streams: Read Strings • No String-reading methods in System.in • To read strings from keyboard • First wrap System.in inside InputStreamReader object • InputStreamReader anInputStreamReader • = new InputStreamReader(System.in); Programming and Problem Solving With Java

  19. Input Streams: Read Strings • Next, wrap InputStreamReader object in BufferedReader object • InputStreamReader anInputStreamReader • = new InputStreamReader(System.in); • BufferedReader inStream = new BufferedReader(anInputStreamReader); Programming and Problem Solving With Java

  20. Input Streams: Read Strings • Can combine these two statements • BufferedReader inStream • = new BufferedReader(new InputStreamReader(System.in)); • InputStreamReader & BufferedReader in java.io.* • Must import java.io.*; • Skeleton for reading • import java.io.*; • class ClassName • { • public static void main(String[] args) • throws java.io.IOException • { • // Create a buffered input stream and attach it to standard • // input • BufferedReader inStream • = new BufferedReader(new InputStreamReader(System.in)); • ... • } • } Programming and Problem Solving With Java

  21. Input Streams: Read Strings • Methods in BufferedReader • read(): Use same as System.in.read() • readLine(): Returns complete line typed by user • Example: Read user's name • // Reads a user's first name, middle initial, • // and last name. Demonstrates use of InputStreamReader, • // BufferedReader and the readLine() method. • import java.io.*; • class ReadInputAsString • { • public static void main(String[] args) • throws java.io.IOException • { • String firstName, lastName; • char middleInitial; • // Create an input stream and attach it to the standard • // input stream • BufferedReader inStream • = new BufferedReader(new InputStreamReader(System.in)); Programming and Problem Solving With Java

  22. Input Streams: Read Strings • Example: continued • // Read a line from the user as a String • System.out.print("Enter your first name: "); • System.out.flush(); • firstName = inStream.readLine(); • // Read a character from the user • System.out.print("Enter your middle initial and last name: "); • System.out.flush(); • middleInitial = (char) inStream.read(); • // Read a line from the user as a String • lastName = inStream.readLine(); • // Display the strings • System.out.println(); • System.out.println("Your name is " + firstName + " " • + middleInitial + ". " + lastName); • } • } Enter your first name: Linda Enter your middle initial and last name: EJones Your name is Linda E. Jones Programming and Problem Solving With Java

  23. To read a number from keyboard (int, double, ...) Define a NumberFormat object Define BufferedReader object Use BufferedReader object to Read response as a string Use NumberFormat object to parse string into Number object Convert Number object to primitive type Input Streams: Read Numbers Programming and Problem Solving With Java

  24. Input Streams: Read Numbers • Code to read a number from keyboard (int, double, ...) • Define a NumberFormat object • NumberFormat aNumberFormatter = NumberFormat.getInstance(); • Define BufferedReader object • BufferedReader inStream • = new BufferedReader(new InputStreamReader(System.in)); • Read response as a string • System.out.print("Enter an integer: "); • System.out.flush(); • String response = inStream.readLine(); • Use NumberFormat object to parse string into Numberobject • Number aNumberObject = aNumberFormatter.parse(response); • Convert Number object to primitive type • int intNumber = aNumberObject.intValue(); Programming and Problem Solving With Java

  25. Input Streams: Read Numbers • Can combine reading, parsing, conversion steps • import java.io.*; • import java.text.NumberFormat; • class ReadAnInt2 • { • public static void main(String[] args) • throws java.io.IOException, java.text.ParseException • { • // Create an input stream and attach it to the standard • // input stream • BufferedReader inStream • = new BufferedReader(new InputStreamReader(System.in)); • // Create a number formatter object • NumberFormat aNumberFormatter = NumberFormat.getInstance(); • // Prompt for input • System.out.print("Enter an integer: "); • System.out.flush(); • // Read the response from the user, convert to Number, • // then convert to int • int intNumber • = aNumberFormatter.parse(inStream.readLine()).intValue(); • // Display the value • System.out.println("You typed " + intNumber); • } • } Note ParseException! Programming and Problem Solving With Java

  26. Input Streams: Multiple Values • To read severalvalues on one line • Use StringTokenizer object • Breaks onestring into parts • Must still convertnumbers (ifnecessary) Programming and Problem Solving With Java

  27. Input Streams: Multiple Values • How to use StringTokenizer • Get string to break apart somehow • Initialize object with string to break apart • StringTokenizer tokenizer = new StringTokenizer("42 58"); • Use nextToken() method to get parts • String token; • token = tokenizer.nextToken(); • System.out.println(token); // Displays 42 • token = tokenizer.nextToken(); • System.out.println(token); // Displays 58 • Can use hasMoreTokens() method to find last one • StringTokenizer tokenizer = new StringTokenizer("42 58"); • while (tokenizer.hasMoreTokens()) • { • System.out.println(tokenizer.nextToken()); • } Programming and Problem Solving With Java

  28. Text Files • Text file • File that is human-readable with simple tools (type, more, edit, ...) • Variable-length lines • Each line terminated by end-of-line marker • Example: Java source file • Easy to read and write text files • Use same classes and methods as System.in and System.in • Advantage of "streams" approach to I/O Programming and Problem Solving With Java

  29. Text Files: The File Class • Need File object for each file program uses • To define • File inFile = new File("myFile.dat"); • Purpose • Contains informationabout the file • A "placeholder" forthe file • Not the same asthe file Programming and Problem Solving With Java

  30. Text Files: The File Class • Methods in the File class • canRead(): Tells if program can read the file • canWrite(): Tells if program can write to the file • delete(): Deletes the file • exists(): Tells if the file is there • isDirectory(): Tells if the file is really a directory name • isFile(): Tells if the file is a file (not a directory) • length(): Tells the length of the file, in bytes Programming and Problem Solving With Java

  31. Text Files: The File Class • Example of File class • import java.io.*; • class TellIfExists • { • public static void main(String[] args) • throws java.io.IOException • { • File myFile = new File("myFile.dat"); • if (myFile.exists()) • { • System.out.println("myFile.dat exists"); • } • else • { • System.out.println("myFile.dat does not exist"); • } • } • } Programming and Problem Solving With Java

  32. Text Files: Writing to a File • Before writing, make sure either • File doesn't exist • !outFile.exists() • File exists, and is writeable • outFile.exists() && outFile.canWrite() • Combine conditions • !outFile.exists() || outFile.canWrite() • Attach file to a stream • FileWriter object: knows how to write stream to a file • Wrap FileWriter object in BufferedWriter object for efficiency • Wrap BufferedWriter object in PrintWriter object Programming and Problem Solving With Java

  33. Text Files: Writing to a File • Example code • // Initialize the file variable • File outFile = new File("myFile.dat"); • // Make sure that the file either doesn't exist or • // we can write to it • if (!outFile.exists() || outFile.canWrite()) • { • // Create an output stream and attach it to the file • PrintWriter fileOutStream • = new PrintWriter(new BufferedWriter( • new FileWriter(outFile))); • // Write to the file • ... • } • else • { • // Error: Can't write to the file • } Programming and Problem Solving With Java

  34. Text Files: Writing to a File • Use PrintWriter object like System.out • fileOutStream.print("This goes "); • fileOutStream.println("to the file"); • System.out and fileOutStream are both output streams • System.out is PrintStream object • fileOutStream is PrintWriter object • PrintStream and PrintWriter are almost identical (PrintWriter is newer) • print(), println(), flush() work the same • Once done writing to the file, close it • fileOutStream.close(); • Program does this when it end • Good idea to do explicitly, though Programming and Problem Solving With Java

  35. Text Files: Writing to a File • Example • // This program writes a table of squares and • // square roots to the file myfile.dat. • import java.io.*; • class WriteSquaresAndSquareRoots • { • public static void main(String[] args) • throws java.io.IOException • { • // Initialize the output file variable • File outFile = new File("myFile.dat"); • if (!outFile.exists() || outFile.canWrite()) • { • // Create a buffered output stream, wrapped by • // PrintWriter, and attach it to the file • PrintWriter fileOutStream • = new PrintWriter(new BufferedWriter • (new FileWriter(outFile))); • // Write the output to the file • for (int number = 1; number <= 10; number++) • fileOutStream.println(number + "\t" + Math.sqrt(number) • + "\t\t" + number * number); Programming and Problem Solving With Java

  36. Text Files: Writing to a File • Example (continued) • // Close the output stream • fileOutStream.close(); • } • else • { • System.out.println("Problem creating output file "); • } • System.out.println("Done"); • } • } • Contents of file • 1 1.0 1 • 2 1.4142135623730951 4 • 3 1.7320508075688772 9 • 4 2.0 16 • 5 2.23606797749979 25 • 6 2.449489742783178 36 • 7 2.6457513110645907 49 • 8 2.8284271247461903 64 • 9 3.0 81 • 10 3.1622776601683795 100 Programming and Problem Solving With Java

  37. Text Files: Reading from a File • Define File object • File inFile = new File("myFile.dat"); • Before reading, make sure both • File exists and is readable • inFile.exists() && inFile.canRead() • Attach file to a stream • FileReader object: knows how to read stream from a file • Wrap FileReader object in BufferedReader object for efficiency • BufferedReader works on files just like System.in • read(): read a single character, or -1 if EOF • readLine(): read a line, or null if EOF Programming and Problem Solving With Java

  38. Text Files: Reading from a File • Example code • // Initialize the file variable • File inFile = new File("myFile.dat"); • // Make sure the file can be read from • if (inFile.exists() && inFile.canRead()) • { • // Create an input stream and attach it to the file • BufferedReader fileInStream • = new BufferedReader(new FileReader(inFile)); • // Read from the file stream the same way as reading • // from the keyboard • ... • } • else • { • // Error: Can't read from file • } Programming and Problem Solving With Java

  39. Text Files: Reading from a File • Complete example: read() method • // Reads a file and displays the number of digits, • // upper case letters, lower case letters, and other characters • // in the file. • import java.io.*; • class CountLettersDigits • { • public static void main(String[] args) • throws java.io.IOException • { • int nextValue, numUpperCase = 0, numLowerCase = 0, • numDigits = 0, numOther = 0; • char nextChar; • String inputFileName; • // Create a buffered input stream and attach it to standard • // input • BufferedReader inStream • = new BufferedReader(new InputStreamReader(System.in)); • // Get input file name from user • System.out.print("Enter input file name: "); • System.out.flush(); • inputFileName = inStream.readLine(); Programming and Problem Solving With Java

  40. Text Files: Reading from a File • Complete example (continued) • // Initialize the file variable • File inFile = new File(inputFileName); • // Make sure the file can be read from • if (inFile.exists() && inFile.canRead()) • { • // Create an input stream and attach it to the file • BufferedReader fileInStream • = new BufferedReader(new FileReader(inFile)); Programming and Problem Solving With Java

  41. Text Files: Reading from a File • Complete example (continued) • // Read from the file • nextValue = fileInStream.read(); • while (nextValue != -1) • { • nextChar = (char) nextValue; • if (Character.isDigit(nextChar)) • { • numDigits++; • } • else if (Character.isUpperCase(nextChar)) • { • numUpperCase++; • } • else if (Character.isLowerCase(nextChar)) • { • numLowerCase++; • } • else • { • numOther++; • } • nextValue = fileInStream.read(); • } Programming and Problem Solving With Java

  42. Text Files: Reading from a File • Complete example (continued) • // Close the stream • fileInStream.close(); • // Display results • System.out.println("Number of digits: " • + numDigits); • System.out.println("Number of upper case letters: " • + numUpperCase); • System.out.println("Number of lower case letters: " • + numLowerCase); • System.out.println("Number of other characters: " • + numOther); • } • else • { • System.out.println("Can't read " + inputFileName); • } • } • } Input file: CountCharacters.java Number of digits: 7 Number of upper case letters: 96 Number of lower case letters: 1001 Number of other characters: 832 Programming and Problem Solving With Java

  43. Text Files: Reading from a File • Complete example: readLine() method • // This program reads a file and displays the file • // on the screen, with a line number before each line. • import java.io.*; • class DisplayLinesWithLineNumbers • { • public static void main(String[] args) • throws java.io.IOException • { • String inputFileName; • String line; • int lineNumber = 0; • // Create a buffered input stream and attach it to standard • // input • BufferedReader inStream • = new BufferedReader(new InputStreamReader(System.in)); • System.out.println("--- File Lister ---"); • System.out.println(); Programming and Problem Solving With Java

  44. Text Files: Reading from a File • Complete example (continued) • // Get file name from user • System.out.print("Enter input file name: "); • System.out.flush(); • inputFileName = inStream.readLine(); • // Initialize the input file variable • File inFile = new File(inputFileName); • if (inFile.exists() && inFile.canRead()) • { • // Create an input stream and attach it to the file • BufferedReader fileInStream • = new BufferedReader(new FileReader(inFile)); • System.out.println(); • System.out.println("--- Contents of file " • + inputFileName + "---"); Programming and Problem Solving With Java

  45. Text Files: Reading from a File • Complete example (continued) • // Read lines from the input stream, display on screen • line = fileInStream.readLine(); • while (line != null) • { • lineNumber++; • System.out.println(lineNumber + ":\t" + line); • line = fileInStream.readLine(); • } • System.out.println("--- End of file ---"); • // Close the stream • fileInStream.close(); • } • else • { • System.out.println("Couldn't open input file " • + inputFileName); • } • } • } --- File Lister --- Enter input file name: JavaTemplate.java --- Contents of file JavaTemplate.java--- 1: class JavaTemplate 2: { ... --- End of file --- Programming and Problem Solving With Java

  46. Text Files: Reading Numbers • Same techniques as reading from keyboard • Get string value from a file • Use NumberFormat object to convert to Number object • Convert Number object primitive type • Example • // Reads a file of numbers, square roots, and • // squares from myfile.dat and displays the contents on the • // screen. Each line of the file should have an integer, the • // square root of that integer, and the square of that integer. • // (Use the program in Listing 6.15 to create the file.) • import java.io.*; • import java.util.StringTokenizer; • import java.text.NumberFormat; Programming and Problem Solving With Java

  47. Text Files: Reading Numbers • Example (continued) • class ReadSquaresAndSquareRoots • { • public static void main(String[] args) • throws java.io.IOException, java.text.ParseException • { • String line; • int number, lineNumber = 0; • double squareOfNumber, squareRootOfNumber; • // Create a number formatter object • NumberFormat aNumberFormatter = NumberFormat.getInstance(); • // Initialize the input file variable • File inFile = new File("myfile.dat"); • if (inFile.exists() && inFile.canRead()) • { • // Create an input stream and attach it to the file • BufferedReader fileInStream • = new BufferedReader(new FileReader(inFile)); Programming and Problem Solving With Java

  48. Text Files: Reading Numbers • Example (continued) • // For each line in the input stream, read an integer and • // two doubles (the square of the number and the square • // root) and display each value. • line = fileInStream.readLine(); • while (line != null) • { • lineNumber++; • // Initialize the tokenizer with the last read line • StringTokenizer tokenizer = new StringTokenizer(line); • // Break the line into an int and two doubles • number • = aNumberFormatter.parse(tokenizer.nextToken()).intValue(); • squareRootOfNumber • = aNumberFormatter.parse(tokenizer.nextToken()).doubleValue(); • squareOfNumber • = aNumberFormatter.parse(tokenizer.nextToken()).doubleValue(); • // Dislay the line's contents • System.out.println("Line " + lineNumber + " contents:"); • System.out.println(" number is " + number); • System.out.println(" square root of " + number + " is " • + squareRootOfNumber); • System.out.println(" square of " + number + " is " • + squareOfNumber); • // Read the next line • line = fileInStream.readLine(); • } Programming and Problem Solving With Java

  49. Text Files: Reading from a File • Example (continued) • // Close the stream • fileInStream.close(); • } • else • { • System.out.println("Couldn't open input file"); • } • } • } Line 1 contents: number is 1 square root of 1 is 1.0 square of 1 is 1.0 Line 2 contents: number is 2 square root of 2 is 1.4142135623730951 square of 2 is 4.0 Line 3 contents: number is 3 square root of 3 is 1.7320508075688772 square of 3 is 9.0 ... Line 10 contents: number is 10 square root of 10 is 3.1622776601683795 square of 10 is 100.0 Programming and Problem Solving With Java

  50. Text Files: Reading from a File Characters Lines Words • Example: Count characters, lines, words • To count characters: increment for each BufferedRead.read() • To count lines: increment for each '\n' • Counting words is trickier • Incremental design and development • Get easy parts written and tested first • Add other features one at a time to the working framework • Advantage: bug is most likely in most recently added part of program Programming and Problem Solving With Java

More Related