עקרונות תכנות מונחה עצמים תרגול :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 Write 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) { throw new AbortException() ; } 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 ? 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: 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