Suppose we want to be able to create a Bank objectfrom a serialized version on a
ID: 3612915 • Letter: S
Question
Suppose we want to be able to create a Bank objectfrom a serialized version on a file (if one exists). Write amethod getBank which is consistent with the following client code.(A "client" of Bank is any software that uses Bank but which is nota member of Bank -- in our case it will be code in BankGui
String fileName ="/home/doug/my.bnk";
Bank myB =Bank.getBank(fileName); //makes myB from serializeddata
if(myB ==null){ //if file did not contain anobject of type Bank
System.out.println("A NewBank");
myB = newBank(fileName); //makes empty Bank that usesfilename
Explanation / Answer
Having a serialized version on file...it sounds as though youmight be able to use ObjectInputStreamand ObjectOutputStream. The onlything you have to do to Bank is add that it implements java.io.Serializable - which just notes that itcan be serialized. To read from a file: public Bank getBank(Stringfile) { try { // create new input stream ObjectInputStreamin=new ObjectInputStream(new FileInputStream(newFile(file))); // read object Bankbank=(Bank)in.readObject(); // close stream in.close(); returnbank; } catch(IOExceptionex) { out.println("Cannotfind file."); } catch(ClassNotFoundExceptionex2) { out.println("Objectis not a bank."); } returnnull; } To write objects to the file: public void save(Bank bank, Stringfile) { try { // create output ObjectOutputStreamout=new ObjectOutputStream(new FileOutputStream(newFile(file))); // write bank out.writeObject(bank); out.close(); } catch(IOExceptionex) { out.println("Cannotfind file."); } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.