Saving Objects Object Oriented Programming 2016375 - 5 Camilo López

Outline • • • • •

Introduction The Class File Reading from a file Writing to a file Object Serialization

Introduction • What have we done so far?

There’s a triggering event *Any request from client code

Introduction • What have we done so far?

An object is created…

Introduction • What have we done so far?

An object is created… Maybe several objects

Introduction • What have we done so far?

There’s a communication between the objects…

Introduction • What have we done so far?

…In order to comply with the request

Introduction • What have we done so far?

. where do you get the necessary information?

…In order to comply with the request

Introduction • What have we done so far?

. where do you get the necessary information?

…In order to . comply with the request what do you do with the answer?

Introduction • The application provides no means of remembering the state of the objects from one invocation of the application to the next. – Whenever we run a Java application, all objects that we instantiate reside in memory allocated to the JVM. When such an application terminates, all of the JVM’s memory is released back to the operating system, and the internal states of all of the objects created by the application are forgotten, unless they have been persisted (saved). Persistent Data Storage

Database Serializable Objects

Files

The Class File • The Class File is particularly useful for retrieving information about files or directories from disk. Objects of class File do not open files or provide any file-processing capabilities. – Class File provides four constructors.

File fileName = new File(String path);. Creates a new File instance by converting the given pathname string into an abstract pathname

File f = new File(C:\file.txt); File names = new File(newFile.dat); For more info: http://java.sun.com/javase/6/docs/api/java/io/File.html

The Class File Method boolean canRead()

boolean canWrite()

boolean exists()

boolean isFile() boolean isDirectory()

Description Returns true if a file is readable by the current application; false otherwise. Returns true if a file is writable by the current application; false otherwise. Returns TRue if the name specified as the argument to the File constructor is a file or directory in the specified path; false otherwise. Returns true if the name specified as the argument to the File constructor is a file; false otherwise. Returns true if the name specified as the argument to the File constructor is a directory; false otherwise.

The Class File Method String getAbsolutePath()

Description Returns a string with the absolute path of the file or directory.

String getName()

Returns TRue if the arguments specified to the File constructor indicate an absolute path to a file or directory; false otherwise. Returns a string with the name of the file or directory.

String getPath()

Returns a string with the path of the file or directory.

String getParent()

Returns a string with the parent directory of the file or directory (i.e., the directory in which the file or directory can be found).

boolean isAbsolute()

Reading from a File .

}

FileReader fr = new FileReader(nameOfFileToBeReadFrom); BufferedReader bIn = new BufferedReader(fr); String line = bIn.readLine(); while (line != null) { // Process the most recently read line however we'd like ... line = bIn.readLine(); } bIn.close();

Instantiate a FileReader, and pass it into a BufferedReader.

Reading from a File

.

}

FileReader fr = new FileReader(nameOfFileToBeReadFrom); BufferedReader bIn = new BufferedReader(fr); String line = bIn.readLine(); while (line != null) { // Process the most recently read line however we'd like ... line = bIn.readLine(); } bIn.close();

Read the first line from the file.

Reading from a File

.

}

FileReader fr = new FileReader(nameOfFileToBeReadFrom); BufferedReader bIn = new BufferedReader(fr); String line = bIn.readLine(); while (line != null) { // Process the most recently read line however we'd like ... line = bIn.readLine(); } bIn.close();

As long as the end of the file hasn't been reached ...

Reading from a File

.

}

FileReader fr = new FileReader(nameOfFileToBeReadFrom); BufferedReader bIn = new BufferedReader(fr); String line = bIn.readLine(); while (line != null) { // Process the most recently read line however we'd like ... line = bIn.readLine(); } bIn.close();

Close the BufferedReader, which automatically closes the encapsulated FileReader, as well.

Writing to a File .

}

FileOutputStream fos = new FileOutputStream(nameOfFileToBeWrittenTo); PrintWriter pw = new PrintWriter(fos); while (we still have more data to output) { pw.println(whatever data we wish to output); } pw.close();

Instantiate a FileOutputStream, and pass it into a PrintWriter.

Writing to a File .

}

FileOutputStream fos = new FileOutputStream(nameOfFileToBeWrittenTo); PrintWriter pw = new PrintWriter(fos); while (we still have more data to output) { pw.println(whatever data we wish to output); } pw.close();

FileOutputStream(String filename, boolean append) Instantiate a FileOutputStream, and pass it into a PrintWriter.

Writing to a File

.

}

FileOutputStream fos = new FileOutputStream(nameOfFileToBeWrittenTo); PrintWriter pw = new PrintWriter(fos); while (we still have more data to output) { pw.println(whatever data we wish to output); } pw.close();

Close the PrintWriter, which automatically closes the encapsulated FileOutputStream, as well.

Object Serialization import java.io.Serializable; .public class ClassName implements Serializable{1}

}

FileOutputStream fs = new FileOutputStream(nameOfFileToBeWrittenTo); ObjectOutputStream os = new ObjectOutputStream(fs); while (we still have more data to output) { os.writeObject(ObjectX); } os.close();

If you want your class to be serializable, implement Serializable

Object Serialization import java.io.Serializable; public class ClassName implements Serializable{1} .

}

FileOutputStream fs = new FileOutputStream(nameOfFileToBeWrittenTo); ObjectOutputStream os = new ObjectOutputStream(fs); while (we still have more data to output) { os.writeObject(ObjectX); } os.close(); Instantiate a FileOutputStream, and pass it into an ObjectOutputStream

Object Serialization import java.io.Serializable; public class ClassName implements Serializable{1} .

}

FileOutputStream fs = new FileOutputStream(nameOfFileToBeWrittenTo); ObjectOutputStream os = new ObjectOutputStream(fs); while (we still have more data to output) { os.writeObject(ObjectX); } os.close(); Instantiate a FileOutputStream, and pass it into an ObjectOutputStream An ObjectOutputStream lets you write objects, but it can’t directly connect to a file.

Object Serialization import java.io.Serializable; public class ClassName implements Serializable{1}

.

}

FileOutputStream fs = new FileOutputStream(nameOfFileToBeWrittenTo); ObjectOutputStream os = new ObjectOutputStream(fs); while (we still have more data to output) { os.writeObject(ObjectX); } os.close();

Write the Objects

Object Serialization import java.io.Serializable; public class ClassName implements Serializable{1}

.

}

FileOutputStream fs = new FileOutputStream(nameOfFileToBeWrittenTo); ObjectOutputStream os = new ObjectOutputStream(fs); while (we still have more data to output) { os.writeObject(ObjectX); } os.close();

Close the ObjectOutputStream, which automatically closes the encapsulated FileOutputStream, as well.

Object Deserialization .

}

FileInputStream fs = new FileInputStream(nameOfFileToBeReadFrom); ObjectInputStream is = new ObjectInputStream(fs); String line = bIn.readLine(); while (true) { // Process the object however we'd like ... Object one = is.readObject(); ObjectX oXName = (ObjectX) one; } is.close(); Instantiate a FileInputStream, and pass it into an ObjectInputStream An ObjectOutputStream lets you read objects, but it can’t directly connect to a file.

Object Deserialization

.

}

FileInputStream fs = new FileInputStream(nameOfFileToBeReadFrom); ObjectInputStream is = new ObjectInputStream(fs); String line = bIn.readLine(); while (true) { // Process the object however we'd like ... Object one = is.readObject(); ObjectX oXName = (ObjectX) one; } is.close();

read the Objects

Object Deserialization

.

}

FileInputStream fs = new FileInputStream(nameOfFileToBeReadFrom); ObjectInputStream is = new ObjectInputStream(fs); String line = bIn.readLine(); while (true) { // Process the object however we'd like ... Object one = is.readObject(); ObjectX oXName = (ObjectX) one; } is.close();

cast the Objects

Object Deserialization

.

}

FileInputStream fs = new FileInputStream(nameOfFileToBeReadFrom); ObjectInputStream is = new ObjectInputStream(fs); String line = bIn.readLine(); while (true) { // Process the object however we'd like ... Object one = is.readObject(); one; ObjectX oXName = (ObjectX) is.readObject(); } is.close();

OR, read AND cast the Objects

Object Deserialization

.

}

FileInputStream fs = new FileInputStream(nameOfFileToBeReadFrom); ObjectInputStream is = new ObjectInputStream(fs); String line = bIn.readLine(); while (true) { // Process the object however we'd like ... Object one = is.readObject(); one; ObjectX oXName = (ObjectX) is.readObject(); } is.close();

Close the ObjectInputStream, which automatically closes the encapsulated FileInputStream, as well.

Object Serialization The instance variables are saved to the file along with a little more info the JVM needs to restore the object

The JVM determines (through info stored with the serialized object) the object’s class type What happens with the object’s constructor? What features are restored? What about static variables? Are they serialized?

Object Serialization What features are restored? Serialization is all or nothing. Either the entire serialization graph is serialized correctly or serialization fails.

You can’t serialize an object if one of its instance variables refuses to be serialized!

Object Serialization What features are restored? Serialization is all or nothing. Either the entire serialization graph is serialized correctly or serialization fails.

You can’t serialize an object if one of its instance variables refuses to be serialized!

Mark an instance variable as transient if it can’t or (shouldn’t be) saved

Object Serialization A a1 = new A("one", 1 ); A a2 = new A("two", 2 ); try{ FileOutputStream fs = new FileOutputStream("test.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(a1); os.writeObject(a2); os.close(); } catch (IOException ex){ ex.printStackTrace(); } a2 = null; //1

Object Serialization //.. try { System.out.println(a1.getX() + " " + a1.getY()); System.out.println(a2.getX() + " " + a2.getY()); } catch (NullPointerException e) { System.out.println("An object doesn't exist!"); try{ FileInputStream fs = new FileInputStream("test.ser"); ObjectInputStream is = new ObjectInputStream(fs); System.out.println("After deserialization"); a1 = (A) is.readObject(); a2 = (A) is.readObject(); System.out.println(a1.getX() + " " + a1.getY()); System.out.println(a2.getX() + " " + a2.getY()); is.close(); }catch (Exception ex){ ex.printStackTrace(); }

References • J. Barker, Beginning Java Objects: From Concepts To Code, Second Edition, Apress, 2005. • H.M. Deitel and P.J. Deitel, Java How to Program: Early Objects Version, Prentice Hall, 2009. • K. Sierra and B. Bates, Head First Java, 2nd Edition, O'Reilly Media, 2005.

Saving Objects

String. getAbsolutePath(). Returns a string with the absolute path of the file or directory. boolean isAbsolute(). Returns TRue if the arguments specified to the File ...

625KB Sizes 1 Downloads 202 Views

Recommend Documents

SAVING CHILD MIGRANTS WHILE SAVING OURSELVES.pdf ...
hurricane and earthquakes more than a decade ago pales in comparison with the. very real ... SAVING CHILD MIGRANTS WHILE SAVING OURSELVES.pdf.

Seed Saving
El Cerrito Community Garden Network Seed Libraries https://sites.google.com/site/elcerritocommunitygarden/seed-library. There are two seed libraries in El Cerrito: • El Cerrito Recycling Center. 7501 Schmidt Lane. In the Recycling Center office, op

Saving Dallas.pdf
Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. Saving Dallas.pdf. Saving Dallas.pdf. Open. Extract. Open with.

Saving Europe?
Nov 21, 2014 - “Austerity and Economic Growth: Concepts for Europe. ... The economic slowdown, increased transfer payments, financial system ...... database for capital stocks for the six countries with enough data coverage (Austria, ...

Saving Sam.pdf
Unfortunately, the only tools you can use to accomplish this task are paperclips. (1 per person, or you can give. them 2 per person). You cannot touch Sam, the boat, or the life preserver with your bare hands. A gummy worm is used to represent Sam, a

SAVING BRAINS - Grand Challenges Canada
Oct 7, 2014 - projects to save brains of children in developing countries. Toronto ..... Novel SMS-based technology for early brain development support and ...

Energy Saving Tips.pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. Energy Saving ...

Read PDF Saving Capitalism
... Capitalism For the Many Not the Few Kindle Cloud Reader Read instantly in your browser Praise for Robert B Reich ’s Saving Capitalism The Paperback ...

U5 DAY 9 - saving mortgages.pdf
Most lending institutions allow mortgage payments to be monthly, bi-monthly (twice a month), Accelerated. bi-weekly (every 2 weeks) or weekly. The difference ...

Saving Sydney - Jenny Lyn.pdf
Dafne AriannysG Carola Shaw. Cami G. Lectura Final: Aimetz. Diseño. Jennii. Page 3 of 159. Saving Sydney - Jenny Lyn.pdf. Saving Sydney - Jenny Lyn.pdf.

Loading/Saving Data and Changing Colours
See ​www.earthbyte.org/Resources/earthbyte_gplates.html​ for EarthByte ... The Manage Feature Collections (Figure 2) window is an alternative way to.

saving excel 2003 as pdf
Page 1 of 1. File: Saving excel 2003 as pdf. Download now. Click here if your download doesn't start automatically. Page 1 of 1. saving excel 2003 as pdf. saving excel 2003 as pdf. Open. Extract. Open with. Sign In. Main menu. Displaying saving excel