CISC 323 (Week 9) Design of a Weather Program & Java File I/O

Similar documents
Simple Java Input/Output

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.

Java Input / Output. CSE 413, Autumn 2002 Programming Languages.

Chapter 10. File I/O. Copyright 2016 Pearson Inc. All rights reserved.

Basic I/O - Stream. Java.io (stream based IO) Java.nio(Buffer and channel-based IO)

Streams and File I/O

1.00 Lecture 30. Sending information to a Java program

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

Overview CSE 143. Input and Output. Streams. Other Possible Kinds of Stream Converters. Stream after Stream... CSE143 Wi

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

HST 952. Computing for Biomedical Scientists Lecture 8

Byte and Character Streams. Reading and Writing Console input and output

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Au

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE. Representation of Primitive Java Types. CSE143 Sp

Lecture 11.1 I/O Streams

Overview CSE 143. Data Representation GREAT IDEAS IN COMPUTER SCIENCE

Programming Languages and Techniques (CIS120)

Unit 10: exception handling and file I/O

CN208 Introduction to Computer Programming

CSC Java Programming, Fall Java Data Types and Control Constructs

CS 200 File Input and Output Jim Williams, PhD

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

Darshan Institute of Engineering & Technology for Diploma Studies

File. Long term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices

CS Week 11. Jim Williams, PhD

Data Structures. 03 Streams & File I/O

Variables of class Type. Week 8. Variables of class Type, Cont. A simple class:

Lecture 22. Java Input/Output (I/O) Streams. Dr. Martin O Connor CA166

When we reach the line "z = x / y" the program crashes with the message:

CS11 Java. Fall Lecture 4

CS 251 Intermediate Programming Java I/O Streams

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Chapter 12. File Input and Output. CS180-Recitation

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

PIC 20A Streams and I/O

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Exceptions and Working with Files

Input from Files. Buffered Reader

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Introduction Unit 4: Input, output and exceptions

Input-Output and Exception Handling

CSE 143 Sp03 Midterm 2 Sample Solution Page 1 of 7. Question 1. (2 points) What is the difference between a stream and a file?

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Streams and File I/O

Object-Oriented Programming Design. Topic : Streams and Files

5/29/2006. Announcements. Last Time. Today. Text File I/O Sample Programs. The File Class. Without using FileReader. Reviewed method overloading.

Question 1. (2 points) What is the difference between a stream and a file?

Sri Vidya College of Engineering & Technology Question Bank

Java Input/Output. 11 April 2013 OSU CSE 1

IT101. File Input and Output

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Streams and File I/O

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

CS112 Lecture: Streams

STREAMS. (fluxos) Objetivos

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Programming Languages and Techniques (CIS120)

Here is a hierarchy of classes to deal with Input and Output streams.

Streams and File I/O

C17: File I/O and Exception Handling

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Here is a hierarchy of classes to deal with Input and Output streams.

CSB541 Network Programming 網路程式設計. Ch.2 Streams 吳俊興國立高雄大學資訊工程學系

CSC 1214: Object-Oriented Programming

Programming Languages and Techniques (CIS120)

Lab 2: File Input and Output

Objec&ves. Review. Standard Error Streams

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

Programming Languages and Techniques (CIS120)

CPS122 Lecture: Input-Output

Chapter 10. IO Streams

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS Programming I: File Input / Output

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

Basic Java IO Decorator pattern Advanced Java IO. Java IO - part 2 BIU OOP. BIU OOP Java IO - part 2

7 Streams and files. Overview. Binary data vs text. Binary data vs text. Readers, writers, byte streams. input-output

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

When working with files and directories, it is often

Compile error. 2. A run time error occurs when the program runs and is caused by a number of reasons, such as dividing by zero.

10/8/2018 Programming Data Structures. class diagram for assignment 08 review: polymorphism review: exception new: File I/O

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

Software Practice 1 - File I/O

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Files and IO, Streams. JAVA Standard Edition

Text User Interfaces. Keyboard IO plus

Simple Java I/O. Part I General Principles

I/O STREAM (REQUIRED IN THE FINAL)

Lab 5: Java IO 12:00 PM, Feb 21, 2018

Full file at

Fundamental Java Syntax Summary Sheet for CISC101, Spring Java is Case - Sensitive!

23 Error Handling What happens when a method is called? 23.1 What is Exception Handling? A.m() B.n() C.p()

CS193j, Stanford Handout #26. Files and Streams

Computer Science is...

Fall 2017 CISC124 10/1/2017

CPS122 Lecture: Input-Output

Transcription:

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