CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming project. Assignment #3: Object-oriented analysis Assignment #4: Detailed project design Assignment #5: Project implementation Assignment #4 Assignment #4 Due Date: Monday, March 15, 2003 (1:00 pm) Move from a statement of the requirements to a design of how your program will be structured to accomplish these goals. Use layered approach business, access, and view (each class should belong to exactly one layer!) Task 1: Big Class Diagram of program [only class names] (6 marks) Task 2: Detailed Class Diagram for each class in Task 1 (6 marks) Task 3: GUI Design [rough pictures of frames and dialogs] (3 marks) Task 4: Sequence diagram [based on use case diagram] (3 marks) Task 5: Activity diagram [for a method with non-trivial loop] (2 marks) TOTAL = 20 marks
Java File I/O Streams A stream is an object that transfers data. Disclaimer: The following overview of Java File I/O and exceptions are slides from CISC 124 (Fall 2003) written by M. Lamb. Input stream: transfers data from a source to the program Output stream: transfers data from the program to a destination CISC 124, fall 2003, I/O 4 Exceptions I/O can throw lots of exceptions: device error file doesn't exist file is protected end of file (in some cases) IOException FileNotFoundException EOFException These are not subclasses of RuntimeException. Compiler will complain if you don't handle them. Difficult to test some error conditions (device errors) Still should write code to handle them Output Streams An OutputStream is an object that knows how to send bytes to a destination A FileOutputStream is an object that knows how to send bytes to a file bytes can be any binary values method in OutputStream: void write(int b) throws IOException creating a FileOutputStream: new FileOutputStream(String name) new FileOutputStream(String name, boolean append) Both can throw FileNotFoundException CISC 124, fall 2003, I/O 5 CISC 124, fall 2003, I/O 6
File Names In Java, a file name is a String that would be a valid file name on your operating system. myfile.txt c:\users\margaret\assignment3.java Warning: backslash is the escape character in Java String filename = "c:\cisc124\data.txt"; Gets compiler error. Two ways around this: 1. Double backslash means a real backslash in the string String filename = "c:\\cisc124\\data.txt"; 2. Java accepts forward slash instead String filename = "c:/cisc124/data.txt"; CISC 124, fall 2003, I/O 7 Write a short message to a file: Simple Example OutputStream outstream = null; // keep compiler happy outstream = new FileOutputStream("OutputTest.txt"); System.out.println("Error in opening output file"); // end try/catch // write to the output stream // write individual bytes outstream.write('h'); outstream.write('e'); outstream.write('l'); outstream.write('l'); outstream.write('o'); System.out.println("Error in writing to output file"); // end try/catch CISC 124, fall 2003, I/O 8 Output Buffering If we run the preceeding program, the file may not contain all the characters we wrote common student debugging problem Reason: output buffering Program data Buffer in memory data File on disk Finishing the Previous Example outstream.close(); System.out.println("error in closing output file"); // end try/catch Now file OutputTest.txt will exist and contain the line: hello When we're done writing to file, we must close the file. This flushes the buffer and frees up system resources OutputStream method: void close() throws IOException CISC 124, fall 2003, I/O 9 CISC 124, fall 2003, I/O 10
Folders Previous example created file with name "OutputTest.txt" Where does this file go (what folder)? Answer: same folder as your program (Java files) Good enough for assignments If you want to create a file in a different folder, must put folder into file name: "subfolder/outputtest.txt" "../otherfolder/outputtest.txt" "c:/myfolder/outputtext.txt" Text Files A FileOutputStream writes individual bytes. Very flexible: bytes can be any values at all not great for writing text files Text File: contains ASCII (or Unicode) characters. Conceptually separated into lines by newline characters ('\n') Examples:.txt,.java,.bat,.html Operating systems have conventions about text files Binary File: contains data coded in binary Examples:.class,.exe,.pdf,.doc (will discuss later) CISC 124, fall 2003, I/O 11 CISC 124, fall 2003, I/O 12 Writer a Writer writes characters to a text file Creating a PrintWriter (1) A PrintWriter object uses an OutputStream Formats the output figures out what characters to write and sends the characters to the OutputStream value: "hello" class PrintWriter: writes formatted text output to a stream methods will look familiar: print println Overloaded to take any primitive type or objects Also a close method. None of these methods throw exceptions. PrintWriter OutputStream sequence of bytes: 'h','e','l','l','o',end of line CISC 124, fall 2003, I/O 13 CISC 124, fall 2003, I/O 14
Creating a PrintWriter (2) To create a PrintWriter, first create an OutputStream OutputStream outstream = null; // keep compiler happy // create the output stream outstream = new FileOutputStream(fileName); System.out.println("Error in opening output file"); // end try/catch Creating a PrintWriter (3) More compressed version: PrintWriter writer = null; writer = new PrintWriter( new FileOutputStream("outputfile.txt")); System.out.println("Error in opening output file"); // create PrintWriter to write formatted output PrintWriter writer = new PrintWriter(outStream); CISC 124, fall 2003, I/O 15 CISC 124, fall 2003, I/O 16 Using the PrintWriter // write a string writer.println("hello, world!"); // write some other types writer.print("the year is "); writer.print(2001); writer.print(", the current temperature is "); writer.println(15.4); writer.print("and my boolean variable is "); boolean b = true; writer.println(b); writer.close() The Standard Output Writing to the "standard output" (the computer screen): System.out.print System.out.println System is a class in the API. System.out is a static field in System type of System.out is PrintStream PrintStream is similar to PrintWriter The file will contain: hello, world! the year is 2001, the current temperature is 15.4 and my boolean variable is true CISC 124, fall 2003, I/O 17 CISC 124, fall 2003, I/O 18
The File Class a File object contains a file name many useful methods: boolean canread() boolean canwrite() boolean delete() boolean exists() long length() constructors: File(String pathname) File(String parent, String child) File(File parent, String child) Can use instead of a file name to create OutputStreams & other I/O objects CISC 124, fall 2003, I/O 19 Example File destination = new File("outputfile.txt"); if (destination.exists()) { System.out.println("Output file exists."); System.out.print( "Do you want to overwrite it (y/n)? "); String answer = Stdin.readString(); if (!answer.equalsignorecase("y")) { System.out.println("aborting"); // end if // end if... outstream = new FileOutputStream(destination); CISC 124, fall 2003, I/O 20 Text Input The preceding slides told you how to write to a text file. Now we need to know how to read from a text file. Using FileReaders Reader has method: int read() throws IOException Reads one character Returns -1 if at end of file Usually don't use FileReader directly a FileReader reads single characters from a text file. Create using a file name or File: FileReader(String filename) throws FileNotFoundException FileReader(File file) throws FileNotFoundException CISC 124, fall 2003, I/O 21 CISC 124, fall 2003, I/O 22
BufferedReader A BufferedReader can read a line at a time -- more convenient Also more efficient because input is buffered. Create a BufferedReader from a simpler reader: BufferedReader(Reader in) Has the read method from Reader, plus an additional method: String readline() throws IOException String returned by readline does not include an end-of-line character When at end of file, readline returns null. Important note: null is different from ""! CISC 124, fall 2003, I/O 23 BufferedReader Example String filename = "sample.txt"; BufferedReader reader = new BufferedReader( new FileReader(filename)); String inputline; // a line of input from the file while (true) { // exit with break inputline = reader.readline(); if (inputline == null) break; System.out.println(inputLine); // end while reader.close(); catch (FileNotFoundException e) { System.out.println("Error: " + filename + " not found"); System.out.println("I/O error while reading"); CISC 124, fall 2003, I/O 24 What About Reading Other Types? BufferedReader can read chars or Strings What about int, double, boolean, etc? There are no methods to read these directly. Instead, read a String and translate into another type String to int: int i = Integer.parseInt(s); String to double: double d = Double.parseDouble(s); These can throw NumberFormatException Example (1) Suppose we expect our input file to have the following contents: int double boolean (each on separate line) Parse methods will throw NumberFormatException if the int & double are not formatted correctly We will use NumberFormatException for other errors as well Important to know what format to expect in file. CISC 124, fall 2003, I/O 25 CISC 124, fall 2003, I/O 26
Example (2) BufferedReader reader = new BufferedReader(...); // read the int String inputline = reader.readline(); if (inputline == null) throw new NumberFormatException(); int theint = Integer.parseInt(inputLine); System.out.println("the integer is: " + theint); Example (3) // read the double inputline = reader.readline(); if (inputline == null) throw new NumberFormatException(); double thedouble = Double.parseDouble(inputLine); System.out.println("the double is: " + thedouble); CISC 124, fall 2003, I/O 27 CISC 124, fall 2003, I/O 28 Example (4) // read the boolean inputline = reader.readline(); if (inputline == null) throw new NumberFormatException(); boolean theboolean; if (inputline.equalsignorecase("true")) theboolean = true; else if (inputline.equalsignorecase("false")) theboolean = false; else throw new NumberFormatException(); System.out.println("the boolean is: " + theboolean); Example, finished catch (NumberFormatException e) { System.out.println("illegal file format"); catch (FileNotFoundException e) { System.out.println("Error: file " + filename + " not found"); System.out.println("I/O error while " + "reading from file"); reader.close(); CISC 124, fall 2003, I/O 29 CISC 124, fall 2003, I/O 30
Java File I/O Resources CISC 323 Website http://www.cs.queensu.ca/~cisc323/2004w/ioexa mples/io.html http://www.cs.queensu.ca/~cisc323/2004w/ioexa mples/schedulewithexceptions.zip http://www.cs.queensu.ca/~cisc323/2004w/ioexa mples/testfiledemo.java Java Website http://java.sun.com/docs/books/tutorial/essential/io/ index.html