1 / 21

Lecture 10 File I/O

Lecture 10 File I/O. This week: Benefits of collections How to create and to use the instance methods of the Vector class How to use the Serializable interface to save objects to files and load objects from files. What are the Benefits of a Collections Framework?.

berg
Télécharger la présentation

Lecture 10 File I/O

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 10File I/O This week: • Benefits of collections • How to create and to use the instance methods of the Vector class • How to use the Serializable interface to save objects to files and load objects from files

  2. What are the Benefits of a Collections Framework? It reduces programming effort: By providing useful data structures and algorithms, a collections framework frees you to concentrate on the important parts of your program, rather than the low-level plumbing required to make it work. By facilitating interoperability among unrelated APIs, the collections framework frees you from writing oodles of adapter objects or conversion code to connect APIs. Taken from http://www.iam.ubc.ca/guides/javatut99/collections/intro/index.html during Nov 2009

  3. What are the Benefits of a Collections Framework? (2) It increases program speed and quality: The collections framework does this primarily by providing high-performance, high-quality implementations of useful data structures and algorithms. Also, because the various implementations of each interface are interchangeable, programs can be easily tuned by switching collection implementations. Finally, because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving the quality and performance of the rest of the program.

  4. What are the Benefits of a Collections Framework? (3) It allows interoperability among unrelated APIs: The collections interfaces will become the "lingua franca" by which APIs pass collections back and forth. If my network administration API furnishes a Collection of node names, and your GUI toolkit expects a Collection of column headings, our APIs will interoperate seamlessly even though they were written independently.

  5. What are the Benefits of a Collections Framework? (4) It reduces the effort to learn and use new APIs: Many APIs naturally take collections on input and output. In the past, each such API had a little "sub-API" devoted to manipulating its collections. There was little consistency among these ad-hoc collections sub-APIs, so you had to learn each one from scratch and it was easy to make mistakes when using them. With the advent of standard collections interfaces, the problem goes away.

  6. What are the Benefits of a Collections Framework? (6) It reduces effort to design new APIs: This is the flip-side of the previous advantage: designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections. They just use the standard collections interfaces. It fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms that operate on objects that implement these interfaces.

  7. Are there any Drawbacks? Historically, collections frameworks have been quite complex, which gave them a reputation for having a steep learning curve. What do you think?

  8. Serialization • We have already seen how to store text in files and how to retrieve it using streams. • Now we will do the same with objects. • This process is called Serialisation. • That’s because every object gets a serial number before it is saved in the stream. • It is easier than with text. • No need to separate numbers from Strings.

  9. Serialization (2) Reading and writing Serializable objects is very similar to reading and writing text : • it is almost always a good idea to use buffering • it is often possible to use abstract base class references, instead of references to concrete classes • there is always a need to pay attention to exceptions; in particular, IOException and ClassNotFoundException The close method : • will automatically flush the stream, if necessary • closing a stream a second time has no consequence

  10. Serializable interface • Each class whose objects will be stored in, or read from a file must implement the Serializable interface. • For example, you could write: public class Car implements Serializable • The serializable interface does not define any methods or constants. • The objects of any class that implements it can be written to or read from a stream using classes from the java.io package.

  11. Saving objects to a file (1) see Program1 in this weeks exercises import java.io.*; public class Program1 { public static void main(String[] args) throws IOException, ClassNotFoundException { String o1="the first one"; String o2 = "the second"; ObjectOutputStream out = null;

  12. Saving objects to a file (2) try { out = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream( "dataFile"))); out.writeObject(o1); out.writeObject(o2); } finally { out.close(); }

  13. Saving objects to a file (3) ObjectInputStream in = null; try { in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("dataFile"))); try { while (true){ System.out.println( in.readObject()); } } Good code or not?

  14. Saving objects to a file (4) catch (EOFException e) {} } finally { in.close(); } } }

  15. toString() • It is always good practice to provide a toString() method in any class you develop. • This tip is especially true when reading objects from an ObjectInputStream as it allows you to display the values to check all is OK.

  16. Further example import java.io.*; import java.util.*; class CarMain { public static void main (String[] args) throws IOException, ClassNotFoundException { List<Car> cars = new ArrayList<Car>(); cars.add(new Car("Ford", "Focus", 2000, 2000)); cars.add(new Car("Nissan","Almera",2002,4000)); cars.add(new Car("Vaxhall","Astra",2000,1500)); cars.add(new Car("Ford","Fiesta",2001,2300)); cars.add(new Car("Fiat","Bravo",1998,900));

  17. Further example (2) for (int i = 0; i<cars.size(); i++) System.out.println(cars.get(i).toString() ); System.out.println("cars set up"); ObjectOutputStream out = null; try { out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("carFile"))); out.writeObject(cars); } finally { out.close(); }

  18. Then read the collect from the file Generates Java warning ObjectInputStream in = null; try { in = new ObjectInputStream(new BufferedInputStream(new FileInputStream("carFile"))); List<Car> newCars = (Array<Car>)in.readObject(); for (int i = 0; i<newCars.size(); i++) System.out.println(newCars.get(i).toString() ); } finally { in.close(); } }//end main }//end class CarMain

  19. Output and Input of Complex Objects from the java.sun site The writeObject and readObject methods are simple to use, but they contain some very sophisticated object management logic. Objects may contain references to other objects. If readObject is to reconstitute an object from a stream, it has to be able to reconstitute all of the objects the original object referred to. These additional objects might have their own references, and so on. In this situation, writeObject traverses the entire web of object references and writes all objects in that web onto the stream. Thus a single invocation of writeObject can cause a large number of objects to be written to the stream.

More Related