עקרונות תכנות מונחה עצמים תרגול 7: כתיבה לקבצים

Slides:



Advertisements
Similar presentations
Chapter 1 Writing a Program Fall Class Overview Course Information –On the web page and Blackboard –
Advertisements

Yoshi
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
James Tam Exception handling in Java Java Exception Handling Dealing with errors using Java’s exception handling mechanism.
James Tam Simple file handling in Java Simple File Input And Output Types of Java files Simple file output in Java Simple file input in Java.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
James Tam Simple File Input And Output Types of Java Files Simple File Output in Java Simple File Input in Java.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Java Review 2. The Agenda The following topics were highlighted to me as issues: –File IO (Rem) –Wrappers (Rem) –Interfaces (Rem) –Asymptotic Notation.
Performance measurements for inter-process communication.
Java Programming: I/O1 Java I/O Reference: java.sun.com/docs/books/tutorial/essential/io/
Java Exception Handling Handling errors using Java’s exception handling mechanism.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
CC1007NI: Further Programming Week 8-9 Dhruba Sen Module Leader (Islington College)
Chapter 10 Exceptions and File I/O. © 2004 Pearson Addison-Wesley. All rights reserved10-2 Exceptions Exception handling is an important aspect of object-oriented.
CS 2511 Fall  Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions:  Examples: Out.
Based on OOP with Java, by David J. Barnes Input-Output1 The java.io Package 4 Text files Reader and Writer classes 4 Byte stream files InputStream, FileInputStream,
עקרונות תכנות מונחה עצמים תרגול 6 - GUI. סיכום ביניים GUI:  Swing  Basic components  Event handling  Containers  Layouts.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
By Rachel Thompson and Michael Deck.  Java.io- a package for input and output  File I/O  Reads data into and out of the console  Writes and reads.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
עקרונות תכנות מונחה עצמים תרגול 8: MVC. Outline  MVC  Using the default models  Example- File Browser.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה. בשבוע שעבר  paint  Graphics  repaint.
עקרונות תכנות מונחה עצמים תרגול 10: Generics. Outline  Generic classes  Generics & Inheritance  Wild Cards  Case study: Generic Graph.
CS 121 – Intro to Programming:Java - Lecture 12 Announcements New Owl assignment up soon (today?) For this week: read Ch 8, sections 0 -3 Programming assignment.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Using Data Files Eric Roberts CS 106A February 22, 2016.
Exercise 1 Review OOP tirgul No Outline Polymorphism Exceptions A design example Summary.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
Programming – Lecture 10 Files, Exception handling (Chapter 12.4)
File I/O CLI: File Input CLI: File Output GUI: File Chooser
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
Five-Minute Review How do we construct a GPolygon object?
File handling and Scanning COMP T1
Reading from a file A file is typically stored on your computers hard drive. In the simplest case, lets just assume it is text. For a program to use.
Introduction to Exceptions in Java
Strings and File I/O.
Introduction to Exceptions in Java
I/O Basics.
Creating and Modifying Text part 2
Exceptions 10-Nov-18.
הרצאה 12: קבצים וחריגות (Exceptions)
Five-Minute Review How do we construct a GPolygon object?
استفاده از فایلها در جاوا
Reading and Writing Text Files
Unit 6 Working with files. Unit 6 Working with files.
Java Exception Very slightly modified from K.P. Chow
Exception Handling in Java
Java Exception Very slightly modified from K.P. Chow
Exceptions handling Try, catch blocks Throwing exceptions.
Java Exceptions Dan Fleck CS211.
Exception Handling Contents
File Input and Output.
Exceptions 10-May-19.
Exceptions one last time…
Exceptions and Exception Handling
FINAL EXAM Final Exam Tuesday, May 3: 1:00 - 3:00 PM (Phys 112)
Observer pattern, MVC, IO & Files
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
Five-Minute Review How do we construct a GPolygon object?
Presentation transcript:

עקרונות תכנות מונחה עצמים תרגול 7: כתיבה לקבצים

Outline Animation The flickering problem File I/O Assignment 3

Outline How to write to a file? Enforcing policy

How to write to a file? Writing to a file sounds simple: Open file Close file

How to write to a file? But what about the exceptions? File or directory not found No permissions No disk space Cannot close file

Write to file – First attempt import java.io.*; public class BadWriteToFile { public void writeToFile() { System.out.println("Please insert filename:"); BufferedReader tIn = new BufferedReader(new InputStreamReader(System.in)); String tFilename = tIn.readLine(); File tFile = new File(tFilename); PrintWriter tOut = new PrintWriter(new FileWriter(tFile)); tOut.println("Hello, World"); tOut.close(); }

Write to file – Second attempt import java.io.*; public class BadWriteToFile { public void writeToFile() { System.out.println("Please insert filename:"); BufferedReader tIn = new BufferedReader(new InputStreamReader(System.in)); try { String tFilename = tIn.readLine(); File tFile = new File(tFilename); PrintWriter tOut = new PrintWriter(new FileWriter(tFile)); tOut.println("Hello, World"); tOut.close(); } catch (IOException e) { e.printStackTrace(); } }}

Write to file – Third attempt public class GoodWriteToFile { private String promptFile() throws AbortException{…} public void writeToFile() throws GiveUpException{…} private void reportError(); private void reportGiveUp(); } promptFile: Read filename from user, throw AbortException if user cancels writeToFile: Try to write to file, try to recover if fail, give up only if user cancels.

The prompt method private String promptFile() throws AbortException { System.out.println(“please insert filename: “); BufferedReader tIn = new BufferedReader( new InputStreamReader(System.in)); try{ String tFilename = tIn.readLine(); if (tFilename == null || tFilename.isEmpty() ) throw new AbortException() ; return tFilename ; } catch ( IOException e) { }

The write method public void writeToFile() throws GiveUpException{ while(true){ try{ String tFilename = promptFile() ; try { PrintWriter tOut = new PrintWriter( new FileWriter (new File(tFilename))); tOut.println(“Hello, World”); tOut.close(); return ; } catch(IOException e) { reportError(); continue; }

The write mthid (cont’d) … } catch (AbortException e) { reportGiveUp() ; throw new GiveUpException(); } } // end of while loop }// end of function

Enforcing Policy Can we make all file access safe ? The OOP way: Different things to write Different prompts (CLI, GUI, …) Different error reports, etc.. The OOP way: Use a base class for file access Concrete classes write to files

The Base Class public abstract class WriteToFileBase { protected abstract File promptFile() throws AbortException; protected abstract void writeInner(FileWriter f)throws IOException; protected abstract void reportError (Exception e); protected abstract void reportGiveUp (Exception e);

WriteToFileBase – Concrete method public void writeToFile() throws GiveUpException { while(true){ try{ File tFile = promptFile(); try { FileWriter f = new FileWriter(tFile); writeInner(f); f.close(); return; }catch(AbortException e){ reportGiveUp(e); throw new GiveUpException(); } } }

How to use WriteToFileBase? It is not always possible to extend base class Other inheritance constrains Cumbersome Redundant Solution Put the code that write to a file in an inner class The inner class extends WriteToFileBase

Inner Class We have already used Inner Class: JButton b = new Jbutton(“Ok”); b.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ … }

Using WriteToFileBase public class ExampleWriteToFile extends Whatever { public void doSomething() { WriteToFileBase tWrite = new WriteToFileBase() { //other methods as before protected void writeInner(FileWriter f) throws IOException { printWriter tOut = new PrintWriter(f); tOut.println(“Hello, World”); } tWrite.writeToFile();

סיכום כתיבה לקובץ Basic Idea: Problem: many exceptions may be thrown Open file Write Close file Problem: many exceptions may be thrown Separate responsibilities to different functions Catch all exception types Enforcing policy: Create Abstract Base Class to Enforce policy Use inner class in concrete classes

עבודה מספר 3