Download presentation
Presentation is loading. Please wait.
1
Strategic Consulting Group IO-1 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. File Input and Output
2
Strategic Consulting Group IO-2 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Objectives l Java File I/O l Stream classes l Readers and Writers l Random Access Files l Object Serialization
3
Strategic Consulting Group IO-3 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Introduction l Reading and writing is accomplished using streams and readers and writers l A stream can be either a source or destination of bytes and are used to implement byte oriented I/O l readers and writers implement Unicode oriented I/O l Input Output classes are defined in java.io package l We start our discussion with the examination of several stream classes. l This is followed by examples of readers and writers, object streams and random access files
4
Strategic Consulting Group IO-4 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Streams l Streams can be compared to a hose that carries data l Just as different sized of pipes can be interconnected, different types of streams can be interconnected l In general, stream classes can be thought of as node streams and filter streams l node streams connect with devices from which a byte stream is read or to which a byte stream is written to l filter streams connect with existing node streams and reorganizes the data bits for use by a program l InputStream class is responsible for reading l OutputStream class is responsible for writing l Both these streams implement byte oriented I/O
5
Strategic Consulting Group IO-5 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. InputStream methods l The input stream has an abstract method to read one byte, and 2 non-abstract methods to read many bytes m int read()-read next byte m int read(byte[] b)-read some bytes into b m int read(byte[] b, int off, int len) - reads up to len bytes and store in b starting with index = off l All of the read methods throw IOException l All of the read methods return the number of bytes read and -1 at End of Stream
6
Strategic Consulting Group IO-6 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. InputStream methods l Other available methods of input stream include m int available() - returns the number of bytes that can be read without interruption by another m void close() - closes the stream and releases resources m void mark(int readlimit) - specifies a logical mark; readlimit defines the boundary of the mark, mark is lost if readlimit is exceeded m boolean markSupported() - tests if the input stream supports mark m void reset() - reposition the stream to the mark m long skip(long n) - skip n bytes
7
Strategic Consulting Group IO-7 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. OutputStream methods l Writing to the stream is conceptually a mirror of reading l OutputStream contains an abstract write method that writes one byte to the output stream, and two non-abstract methods to write many bytes m void write(int b) - write the byte to the stream m void write(byte[] b) - write b.length bytes m void write(byte[] b, int off, int len) - write len bytes from starting from index = off l void close() - close the stream l void flush() - flushes the stream
8
Strategic Consulting Group IO-8 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Implementing a Stream I/O l Both InputStream and OutputStream are abstract classes l Therefore, implementation of these streams are done through subclasses l Example of subclasses of InputStream include m ByteArrayInputStream - Uses an internal byte array as a buffer m FileInputStream - Obtains input from a file m FilterInputStream- Obtains input from some other input stream m ObjectInputStream - Used to read previously serialized objects m PipedInputStream - Sets up a circular buffer in conjunction with a PipedOutputStream; best used with a thread m SequenceInputStream - Multiple input streams can be read in sequence
9
Strategic Consulting Group IO-9 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Implementing a Stream I/O l Examples of subclasses of OutputStream include m ByteArrayOutputStream - data is written to a byte array m FileOutputStream- data is written to a file m FilterOutputStream - Interacts with other streams to transform data from a program to a device specific stream m ObjectOutputStream - serializes an object’s data m PipedOutputStream - Couples with the PipedInputStream l Notice that most input streams have their corresponding output stream classes l Example using FileInputStream and FileOutputStreamwith and without buffer is shown next
10
Strategic Consulting Group IO-10 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. CopyFileUsingByteStream.java import java.io.*; class CopyFileUsingByteStream { public static void main(String [] args) { FileInputStream fis = null; FileOutputStream fos = null; byte inByte; try { fis = new FileInputStream(new File(args[0])); File outFile = new File(args[1]); if (outFile.exists()) { System.out.println("File "+args[1]+" already exists"); return; } else fos = new FileOutputStream(args[1]); Name of the input file Name of the output file
11
Strategic Consulting Group IO-11 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. CopyFileUsingByteStream.java inByte = (byte)fis.read(); while (inByte != -1) { fos.write(inByte); inByte = (byte) fis.read(); } } catch (FileNotFoundException e) { System.out.println ("File not found "+args[0]); } catch (IOException e) { System.out.println(e.getMessage()); } finally { try { if (fis != null) fis.close(); if (fos != null) fos.close(); } catch (IOException e) {} } A source file is copied one byte at a time
12
Strategic Consulting Group IO-12 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. FileCopy.java l Extracts from FileCopy.java is shown l This program is an exact duplicate of the CopyFileUsingByteStream.java, except for the buffered read and the use of available() method byte[] inByte; int size; // code to open file as in the last example size = fis.available(); if (size > 0) { inByte = new byte[size]; fis.read(inByte); fos.write(inByte); }
13
Strategic Consulting Group IO-13 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Data Streams l FileOutputStream and FileInputStream operate using byte oriented output and input - not very useful in many cases l Programs often use ‘binary’ data other than bytes i.e int, float l Data stream classes provide this capability l Data streams derive from Filter streams and do not interact with devices l Data stream classes are normally chained to other streams that do interact with a device l Data Streams provide methods to read and write all basic java data types
14
Strategic Consulting Group IO-14 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Data Streams l There are two data stream classes m DataOutputStream m DataInputStream l These classes are derived from FilterOutputStream and FilterInputStream classes respectively l Examples of write/read methods include writeCharreadChar writeIntreadInt writeDoublereadDouble writeBooleanreadBoolean
15
Strategic Consulting Group IO-15 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Data Streams l Other methods void flush()- flush the output stream l The general chaining process of a data stream (filter) to a node stream (FileInput) can be shown as follows Node device Node streamFilter stream Program Node device Node streamFilter stream Program
16
Strategic Consulting Group IO-16 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Data Input and Output Streams l To set up a data output stream DataOutputStream dos = new DataOutputStream( new FileOutputStream(tempFile)); m tempFile can be a File object or a String l To set up a data input stream DataInputStream dis = new DataInputStream( new FileInputStream(tempFile)); l An example is shown next; this example generates a set of random integers, writes them to a file and then reads them back
17
Strategic Consulting Group IO-17 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestDataStream.java import java.io.*; class TestDataStream { public static void main(String [] args) { DataInputStream dis = null; DataOutputStream dos = null; long writeTime=0, readTime=0; long swTime, ewTime, srTime, erTime; File tempFile = new File("temp.dat"); if (tempFile.exists()) { System.out.println("File temp.dat already exists"); System.out.println("Delete the file and rerun the program"); System.exit(0); } try { dos = new DataOutputStream(new FileOutputStream(tempFile)); swTime = System.currentTimeMillis(); Notice chaining of streams Variables used to measure read write efficiency
18
Strategic Consulting Group IO-18 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestDataStream.java for (int i =0; i < 10000; i++) { dos.writeInt((int)(Math.random()*1000)); } ewTime = System.currentTimeMillis(); writeTime = ewTime - swTime; } catch (IOException e) { System.out.println(e.getMessage()); } finally { try { if (dos != null) dos.close(); } catch (IOException e) {} } // read data try { dis = new DataInputStream(new FileInputStream(tempFile)); srTime = System.currentTimeMillis(); Chaining of streams on the input side
19
Strategic Consulting Group IO-19 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestDataStream.java for (int i = 0; i < 10000; i++) System.out.print(" "+dis.readInt()); erTime= System.currentTimeMillis(); readTime = erTime - srTime; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println(e.getMessage()); } finally { System.out.println("\nWrite = "+writeTime+" Read = "+readTime); try { if (dis != null) dis.close(); } catch (IOException e) {} } Timing discussed after the next example
20
Strategic Consulting Group IO-20 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Efficiency of Data Streams l The I/O, as used in the TestDataStream.java, is still byte oriented and therefore, disk access intensive l Efficiency can be improved by buffering I/O l To set up a buffered stream, we can add a buffering layer to the data stream DataOutputStream dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(tempFile))); l Buffered Streams are also filter classes and provide internal data buffering l Notice chaining of streams through constructors
21
Strategic Consulting Group IO-21 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Extracts from TestBufferedDataStream.java import java.io.*; class TestBufferedDataStream { public static void main(String [] args) { DataInputStream dis = null; DataOutputStream dos = null; // set up code try { dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(tempFile))); for (int i =0; i < 10000; i++) dos.writeInt((int)(Math.random()*1000)); } // other code try { dis = new DataInputStream(new BufferedInputStream( new FileInputStream(tempFile))); for (int i = 0; i < 10000; i++) System.out.print(" "+dis.readInt()); // rest of the code } See source file for the full code
22
Strategic Consulting Group IO-22 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Efficiency of Data Streams l What kind of efficiency is gained? l You will recall that we had embedded time collection statements in the TestDataStream program l We did the same for the next program TestBufferedDataStream.java which uses a buffered stream; both programs are otherwise comparable Write Time(ms)Read Time (ms) Unbuffered9909280 Buffered507850 l Better timing for read can be computed by removing the println that embeds the readInt call
23
Strategic Consulting Group IO-23 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Text Streams l DataStreams are fine if a data file in binary encoded form is already there l It is quite common to read and write human-readable data file l Text file I/O can be done using descendants of Reader and Writer classes l InputStreamReader can be used to read a text stream l OutputStreamWriter can be used to write a text stream l As in the case of data streams, these streams need to be chained to a node stream class
24
Strategic Consulting Group IO-24 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Text Streams l An InputStreamReader can be setup with the following: InputStreamReader in = new InputStreamReader(System.in); l System.in enables a program to read data from the console InputStreamReader in = new InputStreamReader( new FileInputStream(filename)); l Text data can be read from a file, notice chaining l Text reading can also be buffered BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream( new File(filename))));
25
Strategic Consulting Group IO-25 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Encoding Scheme l InputStreamReader and OutputStreamWriter classes can be instantiated with an optional encoding scheme InputStreamReader in = new InputStreamReader( new FileInputStream(filename), encString); m filename can be a File object or a filename string m encString specifies an encoding String m “ 8859_1”ISO Latin-1default for Windows m “Big5”Traditional Chinese m “Cp1253”Windows Greek m “Cp863”PC Canadian French
26
Strategic Consulting Group IO-26 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Reading and writing Text files l It is common to associate text oriented I/O with some file l Special Writer classes exist to write to a file in text format PrintWriter out = new PrintWriter( new FileWriter("testdata.dat")); m PrintWriter class provides a number of overloaded methods for print, println, write for text output l There is no PrintReader class, but only a FileReader class l BufferedReader class has a readLine() method to read an entire line terminated by a new line character
27
Strategic Consulting Group IO-27 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Reading Text files l Text reading from a file can be set up using File input = new File("testdata.dat"); FileReader in = new FileReader(input); BufferedReader br = new BufferedReader(in); l br.readLine(); - returns a String equal to the line terminated by \r or \n, or null at the end of stream l StringTokenizer class can be used to break the line read into tokens provided the string has some delimiter StringTokenizer stk = new StringTokenizer(s,delim); where the delim is the delimiter string
28
Strategic Consulting Group IO-28 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestBufferedReads.java public class TestBufferedReads { public static String getConsoleLine(BufferedReader br) throws IOException { return br.readLine(); } public static void writeDiskFile(PrintWriter out, String s) throws IOException { out.println(s); } public static String[] getColumns(BufferedReader br,String delim) throws NoSuchElementException, IOException { String s = br.readLine(); if ( s == null) return null; StringTokenizer stk = new StringTokenizer(s,delim); int tokenCount = stk.countTokens(); String [] words = new String[tokenCount]; for (int i =0; i < tokenCount; i++) { words[i] = stk.nextToken(); } return words; }
29
Strategic Consulting Group IO-29 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestBufferedReads.java public static void main(String [] args) { InputStreamReader in = null; BufferedReader br = null; FileReader fr = null; PrintWriter out = null; FileWriter fw = null; String inText; String [] fields; String fname = null, lname=null; double salary=0; File input = null; try { in = new InputStreamReader(System.in); br = new BufferedReader(in); fw = new FileWriter("testdata.dat"); out = new PrintWriter(fw); System.out.println("Input for setting up a data file"); System.out.println("Enter three strings: first name, last name, salary"); System.out.println("Separate fields with | or a space");
30
Strategic Consulting Group IO-30 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestBufferedReads.java System.out.println("Terminate input with 'end'"); inText = getConsoleLine(br); while (!(inText.equals("end"))) { writeDiskFile(out,inText); inText = getConsoleLine(br); } } catch (IOException e) { System.out.println(e.getClass().getName()+" "+e.getMessage()); } finally { try{ if (br != null) br.close(); if (out != null) { out.flush(); out.close(); }
31
Strategic Consulting Group IO-31 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestBufferedReads.java }catch (IOException f) { f.printStackTrace(); } try { input = new File("testdata.dat"); in = new FileReader(input); br = new BufferedReader(in); fields = getColumns(br," |"); while ( fields != null) { fname = fields[0]; lname = fields[1]; salary = Double.parseDouble(fields[2]); System.out.println("name = "+lname+", "+fname+" salary: "+salary); fields = getColumns(br," |"); }
32
Strategic Consulting Group IO-32 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestBufferedReads.java } catch (IOException e) { System.out.println(e.getClass().getName()+" "+e.getMessage()); } finally { try { if (br != null){ br.close(); } } catch (IOException f) { f.printStackTrace(); }
33
Strategic Consulting Group IO-33 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. File l Examples used in this section have liberally used files; a brief description of file class is, therefore, in order l The stream and reader/writer classes use files to read from and write to l But a program often needs to know, for example, location of the file, readability, file size, length of contents etc l A File object is the answer to many of these questions l A File object is created using one of 3 constructors File(String pathname); File(File parent, String child); File(String parent, String child);
34
Strategic Consulting Group IO-34 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. File l A number of methods exist to manipulate a File object m boolean canRead() - Can the file be read m boolean canWrite() - Can the file be written to m int compareTo(File pathname) - compare two filenames m boolean createNewFile() - Create a new file only if not there m boolean delete() - Delete the file or directory m boolean exists() - Tests if file is there m String getName() - Return the pathname of the file or directory m boolean isDirectory() - Is the object a directory m boolean isAbsolute() - Tests for absolute pathname m long length() - Length of the file in bytes m String[] list() - list of files and directories for the object; object should be a directory
35
Strategic Consulting Group IO-35 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Random Access Files l Java provides a Random Access file class that can be used to access a record directly RandomAccessFile raf = new RandomAccessFile(ra,mode); m ra - A file object or a file name m mode - usage mode: “r” or “rw” l The file pointer can be set to any location with a seek(long) l Program must provide a means of computing the offset where a record ends and the next record begins l Those interested are referred to the TestRandomFile.java available in the examples directory
36
Strategic Consulting Group IO-36 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Object Persistence l Programs sometimes need to save an Object to a permanent storage to be used by another program l Object can be stored to a file by ‘serializing’ the Object l An ObjectOutputStream is used to write Objects ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream(new File(filename))); l An ObjectInputStream is used to read Objects ObjectInputStream is = new ObjectInputStream( new FileInputStream(new File(filename)));
37
Strategic Consulting Group IO-37 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Object Persistence l Basic method to write to an Object stream writeObject(Object o) writeInt(int i) - Other methods exist to write other primitives l Basic method to read from an Object stream readObject() - returns an Object readInt() - returns a primitive int; other such methods are available
38
Strategic Consulting Group IO-38 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Serializing an Object l All Objects cannot be serialized l An Object can be serialized by implementing Serializable interface public class ObjectStack implements Serializable { // } l Serializable interface does not require implementation of any special method and is considered a marker interface
39
Strategic Consulting Group IO-39 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. What is Serialized l Only data is serialized, not any method l Serialization of specific data members of an Object can be prevented by marking the data as transient public class Account implements Serializable { private transient long accountNumber; private transient long accountBalance; private String accountName; } l Seralized objects of type Account would not include accountNumber or accountBalance
40
Strategic Consulting Group IO-40 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestObjectSerialization.java import java.io.*; import java.util.*; public class TestObjectSerialization { public static void serializeObject(Object o, ObjectOutputStream os) throws IOException { os.writeObject(o); } public static Object unSerializeObject(ObjectInputStream is) throws ClassNotFoundException, IOException { return(is.readObject()); } public static void main(String[] args) { if (args.length < 1) { System.out.println("Usage java TestObjectSerialization "+ ” ” + " "); return; }
41
Strategic Consulting Group IO-41 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestObjectSerialization.java ObjectOutputStream os = null; ObjectInputStream is = null; // A number of hard coded object to be serialized int i = 3; float f = 3.4f; String s = "Java String"; Date d = new Date(); char [] c = {'A','B','C','D','E'}; ObjectStack st = new ObjectStack(); st.push(d); st.push(c); st.push(s); try { os = new ObjectOutputStream( new FileOutputStream(new File(args[0]))); serializeObject(new Integer(i),os); serializeObject(new Float(f),os);
42
Strategic Consulting Group IO-42 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestObjectSerialization.java serializeObject(s,os); serializeObject(d,os); serializeObject(c,os); serializeObject(st,os); os.writeInt(i); os.writeFloat(f); } catch (IOException e) { System.out.println("Error: "+e.getClass().getName()+" "+e.getMessage()); } finally { try { if (os != null) os.close(); } catch (IOException e1) {} }
43
Strategic Consulting Group IO-43 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestObjectSerialization.java // Unserialize, we know the order of serialization try { is = new ObjectInputStream(new FileInputStream(new File(args[0]))); System.out.println("Integer: "+unSerializeObject(is)); System.out.println("Float: "+unSerializeObject(is)); System.out.println("String: "+unSerializeObject(is)); System.out.println("Date: "+unSerializeObject(is)); System.out.println("Char array: "+new String((char[])unSerializeObject(is))); System.out.println("Object stack: "+unSerializeObject(is)); System.out.println("Primitive int: "+is.readInt()); System.out.println("Primitive float: "+is.readFloat()); } catch (ClassNotFoundException cne) { System.out.println("Error: "+cne.getClass().getName()+” ” +cne.getMessage()); } catch (IOException e) {
44
Strategic Consulting Group IO-44 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestObjectSerialization.java System.out.println("Error: "+e.getClass().getName()+" "+e.getMessage()); } finally { try { if (is != null) is.close(); } catch (IOException e1) {} } } // end TestObjectSerialization class class ObjectStack implements Serializable { private Vector v = new Vector(100,20); public void push(Object n) { v.add(n); } public String toString() { return ("ObjectStack with size = "+getHeight()); }
45
Strategic Consulting Group IO-45 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. TestObjectSerialization.java public Object pop() { Object i; int ht; while(v.isEmpty()) { try { this.wait(); } catch (InterruptedException ie) { System.out.println(ie.getClass().getName()+" "+ie.getMessage()); } ht = getHeight(); i = v.remove(ht-1); return(i); } public int getHeight() { return v.size(); }
46
Strategic Consulting Group IO-46 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Versioning Problem l Consider the following scenario m Serialization design is done at Time A and code distributed m A program runs and serializes the object at Time B which is after Time A m Between Time A and B, the object design is changed; the code to unserialize is not changed m THUS WHEN AN OBJECT IS READ BACK, THE DESIGN IS A VERSION OLD l If version mismatch occurs, the program throws an exception l How do we handle such version problem?
47
Strategic Consulting Group IO-47 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Versioning Problem l The obvious solution to versioning problem is to redistribute the byte code when versions are updated. l Redistribution does not solve the problem of reading back old serialized data l We can use the concept of version Identification l Every class is associated with a version Id l The version id for a class can be found by executing the serialver command >serialver ByteCodeFile l The command yields a very long integer i.e the serial id
48
Strategic Consulting Group IO-48 © Copyright 1999-2000 by Santosh Misra. All rights reserved. May not be reproduced in whole or in part by any means without prior written permission. Versioning Problem l The serial version id can be embedded in the class definition public class Account implements Serializable { private final static long serialVersionUID = 3745358160550433574L; // old data members // new data members } l The unserialization process uses the serialVersionUID value instead of generating a new serialized id l New data members are ignored
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.