SWE211 - Lect08 - Binary files PDF
Document Details
Uploaded by ClearerFantasticArt268
Misr International University (MIU)
Tags
Related
- Topic 1.2 Objects_ CS 002-CS21S1 - Advanced Object-Oriented Programming.pdf
- CS0070 Object-Oriented Programming Module 1 PDF
- Object Oriented Programming (2nd Year 1st Sem) PDF
- CCS0023 OBJECT ORIENTED PROGRAMMING Past Paper PDF
- VILLASAN Object-Oriented Programming PDF
- Introduction To Object Oriented Programming PDF
Summary
This document covers Object-Oriented Programming (OOP) concepts, specifically focusing on binary files. It details how I/O is handled in Java, comparing text files with binary files, and delves into binary I/O classes, including FileInputStream/FileOutputStream, DataInputStream/DataOutputStream, and ObjectInputStream/ObjectOutputStream. The document also discusses random access files and file pointers within Java programming.
Full Transcript
Object Oriented Programming SWE211 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 2 How is I/O Handled in Java? A File object encapsulates...
Object Oriented Programming SWE211 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 2 How is I/O Handled in Java? A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perform I/O, you need to create objects using appropriate Java I/O classes. Scanner input = new Scanner(new File("temp.txt")); System.out.println(input.nextLine()); PrintWriter output = new PrintWriter("temp.txt"); output.println("Java 101"); output.close(); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 3 Text File vs. Binary File ❑ Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented in binary form. You cannot read binary files. Binary files are designed to be read by programs. For example, the Java source programs are stored in text files and can be read by a text editor, but the Java classes are stored in binary files and are read by the JVM. The advantage of binary files is that they are more efficient to process than text files. ❑ Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of characters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: '1', '9', '9' in a text file and the same integer is stored as a byte- type value C7 in a binary file, because decimal 199 equals to hex C7. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 4 Binary I/O Classes Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 5 InputStream The value returned is a byte as an int type. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 6 OutputStream The value is a byte as an int type. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 7 FileInputStream/FileOutputStream FileInputStream/FileOutputStream associates a binary input/ output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 8 FileInputStream To construct a FileInputStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 9 FileOutputStream To construct a FileOutputStream, use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append) If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 10 1 2 3 4 5 6 7 8 9 10 TestFileStream Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 11 FilterInputStream/FilterOutputStream Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DatInputStream and DataOutputStream to filter bytes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 12 DataInputStream/DataOutputStream DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 13 DataInputStream DataInputStream extends FilterInputStream and implements the DataInput interface. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 14 DataOutputStream DataOutputStream extends FilterOutputStream and implements the DataOutput interface. Data streams are used as wrappers on existing input and output streams to filter data in the original stream. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 15 Using DataInputStream/DataOutputStream Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors: public DataInputStream(InputStream instream) public DataOutputStream(OutputStream outstream) The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat. DataInputStream infile = new DataInputStream(new FileInputStream("in.dat")); DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat")); TestDataStream Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 16 Concept of pipe line Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 17 Order and Format CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read names using readUTF. Checking End of File TIP: If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? o You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 18 …. FileInputStream fis = null; Example int available = 0; int i = 0; try { // create new file input stream fis = new FileInputStream("clients.txt"); // read till the end of the stream while((i = fis.read())!=-1) { Available: 18; Read: t Available: 17; Read: // available bytes h available = fis.available(); Available: 16; Read: i // convert integer to character Available: 15; Read: s char c = (char)i; Available: 14; Read: Available: 13; Read: // prints i System.out.print("Available: "+available); Available: 12; Read: s System.out.println("; Read: "+c); Available: 11; Read: } Available: 10; Read: a } catch(Exception ex) { Available: 9; Read: // if an I/O error occurs Available: 8; Read: t Available: 7; Read: e ex.printStackTrace(); Available: 6; Read: s } finally { Available: 5; Read: t // releases all system resources from the streams Available: 4; Read: if(fis!=null) { Available: 3; Read: f fis.close(); } Available: 2; Read: i Available: Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. 1; Read: l } All rights reserved. Available: 0; 19 Read: e BufferedInputStream / BufferedOutputStream Buffered input streams read data from a memory area known as a buffer. buffered output streams write data to a buffer. Using buffers to speed up I/O BufferedInputStream/BufferedOutputStream does not contain new methods. All the methods BufferedInputStream/BufferedOutputStream are inherited from the InputStream/OutputStream classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 20 Constructing BufferedInputStream/ BufferedOutputStream // Create a BufferedInputStream public BufferedInputStream(InputStream in) public BufferedInputStream(InputStream in, int bufferSize) // Create a BufferedOutputStream public BufferedOutputStream(OutputStream out) public BufferedOutputStream(OutputStreamr out, int bufferSize) Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 21 Object I/O DataInputStream/DataOutputStream enables you to perform I/O for primitive type values and strings. ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 22 Using Object Streams You may wrap an ObjectInputStream/ObjectOutputStream on any InputStream/OutputStream using the following constructors: // Create an ObjectInputStream public ObjectInputStream(InputStream in) // Create an ObjectOutputStream public ObjectOutputStream(OutputStream out) Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 23 import java.io.ObjectOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class Foo { public static void main(String[] args) { try { ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("numbers.bin")); for (int i = 0; i < 10; i++) { o.writeInt(i); } o.writeLong(65535); o.writeDouble(1); o.writeFloat(2); o.writeChar('A'); o.writeUTF("Hello World"); o.writeObject(new Date()); o.close(); } catch (IOException e) { System.out.println(e); } } } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 24 The Serializable Interface Not all objects can be written to an output stream. Objects that can be written to an object stream is said to be serializable. A serializable object is an instance of the java.io.Serializable interface. So, the class of a serializable object must implement Serializable. The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable. Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays. Java will assign a serial number to each object of the class that it writes to a stream of type ObjectOutputStream. This serial number is then used to re-create the class when it is used with ObjectInputStream. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 25 public class Foo { Example private int x; private String s; if we want to save an instance of public Foo() the Foo class, we could save the { integer x, the String s, into a binary this(100,"hello"); or text file, then read the int and } the String and use it to re-create public Foo(int x, String s) the class. { this.x = x; this.s = s; With serialization we can do this } all in one shot! First here is how public String toString() we could save the object. { return s + " " + x; } We just add the Serializable interface. } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. import java.io.Serializable; Sample code in main() public class Foo implements …. Serializable try { { private int x; ObjectOutputStream o = new private String s; ObjectOutputStream( new FileOutputStream("foo.bin")); public Foo() { Foo foo1 = new Foo(); this(100,"hello"); Foo foo2 = new } Foo(99,"Javaloons"); public Foo(int x, String s) { o.writeObject(foo1); this.x = x; o.writeObject(foo2); this.s = s; o.close(); } } public String toString() { catch (IOException e) return s + " " + x; { } System.out.println(e); } } This creates a file, foo.bin, on the disk, that contains serialized binary versions of foo1 Liang, Introduction to Java Programming, andEdition, Eleventh foo2. All rights reserved. (c) 2018 Pearson Education, Ltd. To read the serialized binary files back in, we use readObject: ……. try catch (FileNotFoundException e) { { ObjectInputStream o = new System.out.println(e); ObjectInputStream( } new FileInputStream("foo.bin")); catch (IOException e) // Note the typecasts below { Foo foo1 = (Foo) o.readObject(); System.out.println(e); Foo foo2 = (Foo) o.readObject(); } System.out.println(foo1); The output is: System.out.println(foo2); hello 100 o.close(); Javaloons 99 } catch (ClassNotFoundException e) { System.out.println(e); } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. public class students implements Serializable{ ……… public int id; students ahmed=new students(); public String fullname; ahmed.fullname="ahmed ali"; public int age; ahmed.id=10; public double []subjectfall;ahmed.subjectfall=56; ahmed.subjectfall=30; ahmed.subjectfall=54; public students() { ObjectOutputStream bin=new subjectfall=new double; ObjectOutputStream(new } FileOutputStream("f:\ } \std.bin")); bin.writeObject(ahmed); bin.close(); ahmed ali ObjectInputStream in=new ObjectInputStream(new FileInputStream("f:\\std.bin")); students x=(students)in.readObject(); Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Serializing Arrays An array is serializable if all its elements are serializable. So, an entire array can be saved using writeObject into a file and later restored using readObject. Here is an example that stores an array of five int values and an array of three strings, and reads them back to display on the console. TestObjectStreamForArray Run Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 30 public class students implements Serializable{ public int id; public String fullname; public int age; public double []subjectfall; public students(int i, String string, int j, double[] scores) { subjectfall=scores; id=i; fullname=string; age=j; } Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. …………… students[] array=new students; double []scores={12,34,54,12,34.5}; array=new students(1,"first name",19,scores); array=new students(1,"second name",29,scores); array=new students(1,"third name",39,scores); array=new students(1,"forth name",49,scores); array=new students(1,"fifth name",59,scores); bin=new ObjectOutputStream(new FileOutputStream("f:\\std.bin" bin.writeObject(array); bin.close(); array=null; in=new ObjectInputStream(new FileInputStream("f:\\std.bin")); array=(students[])in.readObject(); System.out.println(array.fullname); fifth name Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Random Access Files All of the streams you have used so far are known as read- only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 33 RandomAccessFile Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 34 File Pointer A random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt(), the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 35 RandomAccessFile Methods Many methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams. void seek(long pos) throws Sets the offset from the beginning of the IOException; RandomAccessFile stream to where the next read or write occurs. long getFilePointer() IOException; Returns the current offset, in bytes, from the beginning of the file to where the next read or write occurs. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 36 RandomAccessFile Methods, cont. long length()IOException Returns the length of the file. final void writeChar(int v) throws Writes a character to the file as a two-byte IOException Unicode, with the high byte written first. final void writeChars(String s) Writes a string to the file as a sequence of throws IOException characters. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 37 RandomAccessFile Constructor RandomAccessFile raf = new RandomAccessFile("test.dat", "rw"); // allows read and write RandomAccessFile raf = new RandomAccessFile("test.dat", "r"); // read only Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 38 Current file length is 800 The first number is 0 The second number is 1 The tenth number is 9 The new length is 804 The eleventh number is 555 TestRandomAccessFile Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 39 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. Do it.. Check a given line exists in a file Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 41 Do it.. Check a given word exists in a file and prints the number of line that occurs. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 42 Do it.. Display the contents of file, check a given word exists in a file, and counts the number of occurrence. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved. 43 Liang, Introduction to Java Programming, Eleventh Edition, (c) 2018 Pearson Education, Ltd. All rights reserved.