CISC 323 (Week 9) Programming Project Design of a Weather The next - - PowerPoint PPT Presentation

cisc 323 week 9
SMART_READER_LITE
LIVE PREVIEW

CISC 323 (Week 9) Programming Project Design of a Weather The next - - PowerPoint PPT Presentation

CISC 323 (Week 9) Programming Project Design of a Weather The next three assignments form a Program & Java File I/O programming project. Assignment #3: Object-oriented analysis Assignment #4: Detailed project design


slide-1
SLIDE 1

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

Mar 8 & 10, 2004 Jeremy Bradbury (CISC 323)

Programming Project

The next three assignments form a

programming project.

Assignment #3: Object-oriented analysis Assignment #4: Detailed project design Assignment #5: Project implementation

Mar 8 & 10, 2004 Jeremy Bradbury (CISC 323)

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

  • ne layer!)

Mar 8 & 10, 2004 Jeremy Bradbury (CISC 323)

Assignment #4

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

slide-2
SLIDE 2

Mar 8 & 10, 2004 Jeremy Bradbury (CISC 323)

Java File I/O

Disclaimer: The following overview of Java

File I/O and exceptions are slides from CISC 124 (Fall 2003) written by M. Lamb.

CISC 124, fall 2003, I/O 4

A stream is an object that transfers data.

Streams

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 5

I/O can throw lots of exceptions: device error file doesn't exist file is protected end of file (in some cases)

Exceptions

IOException FileNotFoundException EOFException Difficult to test some error conditions (device errors) Still should write code to handle them These are not subclasses of RuntimeException. Compiler will complain if you don't handle them.

CISC 124, fall 2003, I/O 6

An OutputStream is an object that knows how to send bytes to a destination

Output Streams

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

slide-3
SLIDE 3

CISC 124, fall 2003, I/O 7

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

File Names

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 8

OutputStream outStream = null; // keep compiler happy try {

  • utStream = new FileOutputStream("OutputTest.txt");

} catch (IOException e) { System.out.println("Error in opening output file"); System.exit(1); } // end try/catch

Simple Example

// write to the output stream try { // write individual bytes

  • utStream.write('h');
  • utStream.write('e');
  • utStream.write('l');
  • utStream.write('l');
  • utStream.write('o');

} catch (IOException e) { System.out.println("Error in writing to output file"); System.exit(1); } // end try/catch

Write a short message to a file:

CISC 124, fall 2003, I/O 9

If we run the preceeding program, the file may not contain all the characters we wrote – common student debugging problem Reason: output buffering

Output Buffering

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 Program Buffer in memory

data

File on disk

data

CISC 124, fall 2003, I/O 10

try {

  • utStream.close();

} catch (IOException e) { System.out.println("error in closing output file"); } // end try/catch

Finishing the Previous Example

Now file OutputTest.txt will exist and contain the line: hello

slide-4
SLIDE 4

CISC 124, fall 2003, I/O 11

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"

CISC 124, fall 2003, I/O 12

A FileOutputStream writes individual bytes. Very flexible: bytes can be any values at all not great for writing text files

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 13

a Writer writes characters to a text file

Writer

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.

CISC 124, fall 2003, I/O 14

A PrintWriter object uses an OutputStream Formats the output – figures out what characters to write – and sends the characters to the OutputStream

Creating a PrintWriter (1)

PrintWriter OutputStream

value: "hello" sequence of bytes: 'h','e','l','l','o',end of line

slide-5
SLIDE 5

CISC 124, fall 2003, I/O 15

To create a PrintWriter, first create an OutputStream

Creating a PrintWriter (2)

OutputStream outStream = null; // keep compiler happy // create the output stream try {

  • utStream = new FileOutputStream(fileName);

} catch (IOException e) { System.out.println("Error in opening output file"); System.exit(1); } // end try/catch // create PrintWriter to write formatted output PrintWriter writer = new PrintWriter(outStream);

CISC 124, fall 2003, I/O 16

More compressed version:

Creating a PrintWriter (3)

PrintWriter writer = null; try { writer = new PrintWriter( new FileOutputStream("outputfile.txt")); } catch (IOException e) { System.out.println("Error in opening output file"); System.exit(1); }

CISC 124, fall 2003, I/O 17

// 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()

Using the 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 18

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 Standard Output

slide-6
SLIDE 6

CISC 124, fall 2003, I/O 19

a File object contains a file name many useful methods: boolean canRead() boolean canWrite() boolean delete() boolean exists() long length()

The File Class

Can use instead of a file name to create OutputStreams & other I/O objects constructors: File(String pathname) File(String parent, String child) File(File parent, String child)

CISC 124, fall 2003, I/O 20

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"); System.exit(1); } // end if } // end if ....

  • utStream = new FileOutputStream(destination);

CISC 124, fall 2003, I/O 21

The preceding slides told you how to write to a text file. Now we need to know how to read from a text file.

Text Input

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 22

Reader has method:

int read() throws IOException

Reads one character Returns -1 if at end of file

Using FileReaders

Usually don't use FileReader directly

slide-7
SLIDE 7

CISC 124, fall 2003, I/O 23

A BufferedReader can read a line at a time -- more convenient Also more efficient because input is buffered.

BufferedReader

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 24

String filename = "sample.txt";

BufferedReader Example

try { 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"); } catch (IOException e) { System.out.println("I/O error while reading"); }

CISC 124, fall 2003, I/O 25

BufferedReader can read chars or Strings What about int, double, boolean, etc?

What About Reading Other Types?

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 Important to know what format to expect in file.

CISC 124, fall 2003, I/O 26

Suppose we expect our input file to have the following contents: int double boolean (each on separate line)

Example (1)

Parse methods will throw NumberFormatException if the int & double are not formatted correctly We will use NumberFormatException for other errors as well

slide-8
SLIDE 8

CISC 124, fall 2003, I/O 27

Example (2)

try { 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);

CISC 124, fall 2003, I/O 28

// read the double inputLine = reader.readLine(); if (inputLine == null) throw new NumberFormatException(); double theDouble = Double.parseDouble(inputLine); System.out.println("the double is: " + theDouble);

Example (3)

CISC 124, fall 2003, I/O 29

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); reader.close(); }

CISC 124, fall 2003, I/O 30

catch (NumberFormatException e) { System.out.println("illegal file format"); } catch (FileNotFoundException e) { System.out.println("Error: file " + filename + " not found"); } catch (IOException e) { System.out.println("I/O error while " + "reading from file"); }

Example, finished

slide-9
SLIDE 9

Mar 8 & 10, 2004 Jeremy Bradbury (CISC 323)

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