0% found this document useful (0 votes)
38 views

Unit 5 File Handling and Collections Framework - NP Wordpress - Image

Uploaded by

Vansh Kalariya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
38 views

Unit 5 File Handling and Collections Framework - NP Wordpress - Image

Uploaded by

Vansh Kalariya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 25
340701 ‘Subject Name: Advanced Object Oriented Programming Unit No: Subject Code: Unit—5: File Handling and Collections Framework Introduction: ‘When we use variables and array for storing data inside the programs,We face two Problems: 1) The Gata is lost either when a variable goes ont of scope or when the program is terminated. The storage is temporary. 2) It is difficult to handle large volumes of data using variables and arrays, We can overcome these problems by storing data info secondary storage devices, We can store data using concept of files. Data stored in file is often called persistent data * A file is collection of related records placed area on the disk. A record is composed of several fields. Field is a group of characters. Storing and managing data using file is known as file processing Which includes tasks such as creating files, updating files and manipulation of data ‘© Reading and writing of data in a file can be done at the level of bytes or characters or fields depending on the requirement of application java provide capabilities to read and write class object directly. ‘© The process of reading, and writing objects is called serialization. Concept of stream ‘+ In file processing, input refers to the flow of data into a program and output means the flow of data ont of a program. * Input to a program may come from the keyboard, mouse, memory, program. * Output fiom a program may go to the screen, printer, memory disk, network or another program. ‘© Input and output share certain common characteristics like unidirectional movement of data, treating data as a sequence of bytes or characters and support to sequential access to data. ‘* Java uses concept of stream to represent ordered sequence of data, a common characteristics shared by all input/output devices. «A stream in java is a path along which data flows (like pipe along which water flows). It has source (of data) and destination (for that data) Both the source and destination may be physical devices or programs or other streams in same program. + The concept of sending data from one stream to another has made streams in java a powerfil tool for file processing. We can build a complex file processing sequence using a series of simple stream operation. This feature is used to filter data along the pipeline of streams so that ‘we obtain data in desired format. A stream can be defined as a sequence of data. There are two kinds of Streams: a network or another Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 1 ‘Subject Name: Advanced Object Oriented Programming Unit No: 5, Subject Code: 4340701 © InputStream: The InputStream is used to read data from a source © OutputStream: The OutputStream is used for writing data to a destination. Here is hierarchy of classes to deal with Input and Output streams. © Types of Streams: Depending upon the data a stream holds, it can be classified into: + Byte Stream = Character Stream Prepared By: DEPARTMENT OF COMPUTER ENGINEERING. Page 2 ‘Subject Name: Advanced Object Oriented Programming UnitNo: 5 Subject Code: 4340701 ey Cea ug 4 coe Pee een ec Cees) To cee esd Cree Long \ = = =a —a =u Sa Cue e ed prong Sd InputStreamReader | OutputStreamWriter ee AU iy 1. Byte Stream: Byte siream is used to read and write a single byte (8 bits) of data All byte stream classes are derived fiom base abstract classes called InputStream and OutputStream, © Java InputStream Class: > Input stream classes that are used 10 read 8-bit bytes include super class known as InputStream, and a number of subclasses for supporting various input-related funetions, > The super class InputStream is an abstract class. and, therefore, we cannot create instances of this class > Rabter:we mmst use the subclasses that inherit om this class. Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page3 ‘Subject Name: Advanced Object Oriented Programming Unit No: Subject Code: 4340701 The InputStream class defines method for performing input fictions such as: + Reading bytes, = Closing streams, = Marking position in streams, Skipping ahead in a stream, Finding the mmber of bytes in a stream > InputStream Methods: 1. read() : Reads a byte from the input stream 2. read(byte bi) : Reads an array of bytes into b 3. read(byte bj],int n,int m) ; Reads m bytes into b starting from nth byte 4. available() : Gives number of bytes available in the input 5. skip(n) : Skips over n bytes fiom the input stream 6. reset() : Goes back to the beginning of the stream 7. close() : Closes the input stream. + Java OutputStream Class: > Output stream classes are derived from the base class OutputStream as shown in figure. Like InputStream, the OutputStream is an abstract class and therefore we cannot instantiate it. The several subclasses of the OutputStream can be used for performing the cutpat operations. > The OutputStream includes methods that are designed to perform the following task * Writing bytes + Closing stream + Flushing stream > OutputStream Methods: 1. writed : Writes a byte to the output stream 2. write(byte b[]) : Writes all bytes in the array b to the output stream 3. write(byte bl],int n,int m): Writes m bytes from array b starting fiom nth byte 4. closed : Close the output steam 5 flush) Flushes the output stream 2. Character stream classes: ‘© Character stream is used to read and write a single character of data. ‘* All the character stream classes are derived from hase abstract classes Reader and Writer. Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 4 Subject Name: Advanced Object Oriented Program! ng Unit No: Subject Code: 340701 © Java Reader Class: > Reader stream classes are designed to read character from the files. Reader class is the base class for all other classes in this group as shown in figure. > These classes are functionally very similar to the input stream classes, except input stream use bytes as their fiandamental unit of information, while reader stream use characters. } The Reader class contains method they are identical to those available in the InputStream class, except Reader is designed to handle characters. Therefore, reader classes can perform all the fimctions implemented by the input stream classes. © Java Writer Class: > Like output stream classes, the writer stream classes are designed to perform all output operations on files. > Only difference is that while output stream classes are designed to write bytes, the writer stream classes are designed to write characters > The Writer class is an abstract class which acts as a base class for all other writer stream classes > ‘This base class provides support for all output operations by defining method that are identical to those in OutputStream class, + Using the file class: © The java.io package includes a class known as the File class that provides support for creating files and directories. The class incudes several constructors for instantiating the File objects. ‘© File class provides methods for operations like: = Creating a file + Opening a file * Closing a file + Deleting a file = Getting the name of. file = Getting the size of a file = Checking the existence of a file = Renaming a file * Checking whether the file is writable = Checking whether the file is readable © Input/output Exceptions Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 5 ‘Subject Nam \dvanced Object Oriented Program! ng Unit No: Subject Code: 340701 ‘© When creating files and performing 1/O operations on them, the system may generate 10 related exceptions ‘© The basic /O related exception classes and their functions: VO exception class: Function 1 | BOFException Signals that an end of file or end of stream has been teached unexpectedly during input 2 | FileNotFoundException_| Tnforms that a file could not be found 3 | TotermptedIOException | Warns that an /O operations has been interrupted: 4 [TOEXception ‘Signals that an VO exception of some sort has occurred 1. Creation of files: If we want to create and use a disk file, we need to decide the following about the file and its intended purpose: + Suitable name forthe file = Data type to be stored + Pumpose (reading, writing, or updating) = Method of creating the file 2. Reading/writing bytes: * We have used FileReader and FileWriter classes to read and write 16-bit characters, Most file systems use only 8-bit bytes. As pointed out earlier, java i/o system provides a number of classes for handling bytes are FilelnputStream and FileOutputStream classes, We can use them in place of FileReader and file writer. Example-1: Write a program which creates file and writes byte into that file. import java.io.*; public class WriteByte { public statie void main(String args{)) { File nw File( “input txt") \ to create new file Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 6 ‘Subject Nam ng Unit No: \dvanced Object Oriented Program! Subject Code: 340701 FileOutputStream outfile = null; byte cities[] = (TyL'VO"VVE)T AVA; ty ef -write(cities); 3 catch(IOException e) { System.out printha(e); System exit(-1); } System out printin ("Write Byte"); System.out.printin ("Thank You...!!!"); 3 3 Output: Write Byte Thank You!!! Example-2: Write a program which reads byte from file. import java.io.*; public class ReadingByte { public statie void main(String argsf)) Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page7 340701 Subject Code: \dvanced Object Oriented Programming Unit No: { FileTnputStream infile = mull; int b; ny t infile = new FilelnputStream("in.txt"); while((b = infilexead() != -1) { Systemout printin((cha:)b), } infile.close(); 3 cateh(IOException e) a System. out printin("Somry..!! File Not Found. 3 3 } Output : ILOVE JAVA 3. Reading/writing characters > As pointed ont earlier, subclass of Reader and Writer implement streams that can handle characters. The two subclasses used for handling characters in files are FileReader and FileWriter. Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 8 ‘Subject Nam \dvanced Object Oriented Program ng UnitNo: 5 Subject Code: 340701 Example-3 : Write a program which creates file and writes character into that file. import java.io.*; class Character Write t public statie void main(String args{)) t File fl=new File("input Ltxt"); FileWriter fw — null; uy { fw-mew FileWriter(il); fiv.write(“ahmedabad \n" fw write(" baroda \n"); fiv.close(); } catch(FileNotFoundException e) t System out printia("Sorzy..t! File Not Found 3 catch(IOException é) {System out printin(e. getMessageQ); } System.out printin(* write operation done!!”); 3 » Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page? \dvanced Object Oriented Program! ng Unit No: Subject Code: 340701 Output: write operation done Example-4: Write a program which reads character from file. import java.io.*; class Readchar t publie static void main(String args) t FileReader fi =uull; ty {fr new FileReader( input.txt"), int ch; while((ch= fi:tead()) != -1) { System out print((char)ch); a SysteuLout.printia("Reading complete”); fi.close(); 3 catch(FileNotFoundException e) t System ont printla("Sorry..! File Not Found...1!!" } Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 10 ‘Subject Nam \dvanced Object Oriented Program 340701 ng Unit No: 5 Subject Code: catch(IOException e) { System. out printin(e. get Message) i } 3 Output: ahmedabad baroda Reading complete Example -5: Write a program to read one byte at a time from a file and copy it into another file immediately. import java.io.*; class CopyByte t public static void main(String args{]) t uy {byte b-0; FilelnputStream infile = new FilelnputStream("in.txt"); FileOutputStream outfile = new FileOutputStream("‘out-txt"); while(byteread { “1+ Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 11 ‘Subject Nam \dvanced Object Oriented Program! ng Unit No: Subject Code: 4340701 b= (byte)infile read(); outfile.write(b); 3 System_out println("Byte Copied From in.txt to out txt FIle "); } catch(FileNotFoundException e) sf System ont printin("Sorry.1! File Not Fond..." } catch(OException e) { System.out printhn(e getMessage()) } t 3 Output : Byte Copied From in txt to out txt File Example -6: Write a program to merge two files in third file. import java.io.*; class FileMergeDemo ( public static void main(String args{]) t Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 12 ‘Subject Name: Advanced Object Oriented Programming Unit No: 5 Subject Code: 4340701 ty { FileInputStream filel = new FileInputStream ("File1 txt"); FileInputStream file? = new FileInputStream ("File2.1xt") SequenceluputStream file3 = new SequenceluputStream (filel, file2); BufferedInputStream br] = new BufferedInputStream (file3): BufferedOutputSiream br2 = new BufferedOutputStream (System. out); int ch; while((ch = br1.read())!=-1) { ‘br2.,write((char)ch); } br1.close(); br2.close(); filel.closeQ); file? close): System out printin("Merge Two File Sucessfully "); } catch(IOException e) { System. out printla("Sorry..1! File Not Found...!! } 3 # Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 13 \dvanced Object Oriented Program ng Unit No: 5 Subject Code: 340701 Output: Vpmplérp Example -7: Write a program which creates file and perform read and write operations on that file. ‘import java.io.*; public class p30 t public static void main(String args{]) z! File fl=new File("test.xt"); FileOutputStream outfile = mull; byte cities{] = SN ILYONVYBSI'SAYVYAD: ty t outfile= new FileOutputStream( fl); outfile write(cities): } catch(Exception e) { ‘System out println(e); Systemeexit(-1); 3 System.out.printin(" Write operation successfully completed!!!") Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 14 ‘Subject Nam \dvanced Object Oriented Program! ng Unit No: Subject Code: 340701 System. out printin("Thank You...!!!"); FileTnputStream infile = null; int b; uy i infile = new FileputStream("vpmp txt"): while((b = infile.read()) != -1) { System out printha((char)b); 3 infile.close(); 3 cateh(Exception e) a System out printin("Sorry..!! File Not Found...!!"); 3 System. out prinfin("Reading operation successfully completed!!!"); } 3 Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 15 ‘Subject Name: Advanced Object Oriented Programming UnitNo: 5 Subject Code: 4340701 > Collections Framework overview © Any group of individual objects which are represented as a single unit is known as the collection of the objects. ‘© In Java, a separate ffamework named the “Collection Framework” has been defined in IDK 1.2 which holds all the collection classes and interface in it, © The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes. > Whatis a Framework? A framework is a set of classes and interfaces which provide a ready-made architecture. In order to implement a new feature or a class, there is no need to define a framework. > Need for a Separate Collection Framework: Before the Collection Framework (or before JDK: 1.2) was introduced, the standard methods for grouping Java objects (or collections) were Arrays or Veetors, ot Hashlables. All of these collections had no common interface. Therefore, though the main aim of all the collections is the same, the implementation of all these collections was defined independently and had no correlation among them. And also, it is very difficult for the users to remember all the different methods, syntax, and constructors present in every collection class. Let's understand this with an example of adding an element in a Hashtables and a vector. Example1: Java program to demonstrate why collection framework was needed. import java io."; import java.util* class CollectionDemo { publie static void main(String] J args) t #Creating instances of the array, vector and hashtable int arr{] = new int{] { 1, 2,3, 4}; Veetor v= new Vector); Hashtable l= new Hashtable (); 1/ Adding the elements into the vector v.addElemeat (1); v.addElement (2); Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 16 Subject Name: Advanced Object Oriented Program! ng Unit No: Subject Code: 340701 / Adding the element into the hashtable hput (1, "vpmpce"). hput 2, "nehapatel"); (/ Accessing the first element of the atray, vector and hashtable System. out.printIn (arr [0]); System. out printin (v.elementat (0)); System. out println (h.get (1)); Output: 1 1 ypmpce = As we can observe, none of these collections (may, Vector, or Hashtable) implements a standard member access interface, it was very difficult for programmers to write algorithms that can work for all kinds of Collections. = Another drawback is that most of the “Vector’ methods are final, meaning we cannot extend the * Vector” class to implement a similar kind of Collection. = Therefore, Java developers decided to come up with a common interface to deal with the above- mentioned problems and introduced the Collection Framework in IDK 1.2 post which both, legacy Vectors and Hashtables were modified to conform to the Collection Framework. « Advantages of the Collection Framework: > Consistent API: The API has a basic set of interfaces like Collection, Set, List, or Map, all the classes (ArrayList, LinkedList, Vector, etc) that implement these interfaces have some common set of methods, > Reduces programming effort: A programmer doesn’t have to worry about the design of the Collection but rather he can focus ou its best use in bis program, Therefore, the basic concept of Object-oriented programming (ic.) abstraction has been successfully implemented. > Increases program speed and quality: Increases performance by providing high-performance implementations of usefial data structures and algorithms because in this case, the programmer need not think of the best implementation of a specific data structure. He can simply use the best implementation to drastically boost the performance of his algorithn/program. Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 17 ‘Subject Name: Advanced Object Oriented Programming Unit No: 5, Subject Code: © Hierarchy of the Collection Framework: + The utility package, (java.util) contains all the classes and interfaces that are required by the collection framework. = The collection framework contains an interface named an iterable interface which provides the iterator to iterate through all the collections. * This interface is extended by the main collection interface which acts asa root for the collection framework. + All the collections extend this collection interface thereby extending the properties of the iterator and the methods of this interface. * The following figure illustrates the hierarchy of the collection framework. + implements —> tends Prepared By: DEPARTMENT OF COMPUTER ENGINEERING. Page 18 ‘Subject Nam \dvanced Object Oriented Program! ng Unit No: Subject Code: 340701 The classes which implement the List interface are as follows: A. ArrayList: ArrayList provides us with dynamie arrays in Java Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. ‘+ The size of an ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from the collection. © Java ArrayList allows us to randomly access the list. AmayList cannot be used for primitive types, like int, char, etc. We will need @ wrapper class for such cases. Example: Java program to demonstrate the working of ArrayList. import java.io.*; import java.util, class GFG { (/ Main Method public statie void main(String{] args) { Declaring the ArrayList with initial size n AnrayList al = new ArrayList(); ‘/ Appending new elements at the end of the list for (int i= 1; 1<= 5, 4+) aladd(i); Systemout printin(al); alremove(3); Systemout printin(al); for (int i= 0:1 Il = new LinkedL ist(); // Appending new elements at the end of the list for (int i= 1; 1<=5; i++) MaddGi); System out printin(ll); ILremove(3); System out printin(tl); // Printing elements one by one for (int i= 0, 1< ILsizeQ: i) System.out.print(Il-get() +" "); Output: 11.2,3,4,5] 1,2, 3, 5] 1235 Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 20 340701 Subject Code: ‘Subject Name: ng Unit No: \dvanced Object Oriented Program! © The following are the classes that implement the Set interface: A. HashSet ‘© The HashSet class is an inherent implementation of the hash table data structure. * The odjects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects are inserted based on their hashcode * This elass also allows the insertion of NULL elements, Example: Java program to demonstrate the working of a HashSet. {mmpott java.util*; public class HashSetDemo { public static void main(String args[]) {_ HashSet hs = new HashSet(); his.add(VPMP "); 1us.add("Polytechnic") ‘ys.add("Gandhina gas"); hs.add("Weleome To"); his.add(’CE Dept."); _// Traversing elements Iterator itt — hs.iterator(), while (itr-hasNext()) { System.out.prinfin(itr.next()); } } } Output: Gandhinagar Polytechnic VPMP CE Dept Welcome To ++ Map class : HashMap © Map Interface: © A map isa data structure that supports the key-value pair for mapping the data. This interface doesn’t support duplicate keys because the same key cannot have multiple mappings, © However it allows duplicate values in different keys. A map is useful if there is data and we wish to perform operations on the basis of the key. Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 21 ‘Subject Nam 340701 \dvanced Object Oriented Program! ng Unit No: Subject Code: ‘This map interface is implemented by various classes like HashMap, TreeMap, ete. Since all the subclasses implement the map, we can instantiate a map object with any of these classes, For example, Map lun = new HashMap<> 0); Map tm = new TreeMap<> (); Where T is the type of the object. ‘© The frequently used implementation of a Map interface is a HashMap. HashMap: HashMap provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String so that the Indexing and search operations are faster. ‘© HashSet also uses HashMap internally. Example: Java program to demonstrate the working of a HashMap import java.util*: public class HashMapDemo {public static void main(String args[]) {_ /f'Creating HashMap and adding elements HashMap hm ~ new HashMap(); hm put(1, "AOOP"): hm put(2, "VPMP_CE"); hmput(3, "NEHA PATEL"); “Finding the value for a key Systemout printin("Value for 1 is " + hm.get(1)); // Traversing through the HashMap for (Map Entry e- hm entrySet()) System_out printIn(e.getKey() ~ "" + e.getValueQ)); Bb Output: Value for 1 is AOOP 1 AOOP 2 VPMP_CE 3 NEHA PATEL > For-each loop in Java Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 22, ‘Subject Name: Advanced Object Oriented Programming Unit No: Subject Code: 340701 For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Javas. «© Itstarts with the keyword for like a normal for-loop. ‘+ Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name. ‘+ Inthe loop body, you can use the loop variable you created rather than using an indexed array element. + It’s commonly used to iterate over an array ora Collections class (eg, ArrayList) Syntax: for (type var : array) i statements using var; 3 Example: Simple program with for each loop. import java.io.” class Easy, { public static void main(String[] args) t int ar[] = { 10, 50, 60, 80, 90 }; for (int element : ax) System.out.print(element +" ") > Output 105060 80 90 Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 23 ‘Subject Nam 340701 \dvanced Object Oriented Program! ng Unit No: Subject Code: ‘The above syntax is equivalent to: for (int i-0; i maxSoFar) { maxSoFar = mum, } } retum maxSoFar; ) } Output ‘The highest score is 132 Prepared By: DEPARTMENT OF COMPUTER ENGINEERING Page 24 ‘Subject Name: Advanced Object Oriented Programming Unit No: 5 Subject Code: 4340701 ‘© Limitations of for-each loop : 1, For-each loops are not appropriate when you want to modify the array for (int num : marks) { //only changes nam, not the array element mum = num*2; » 2. For-each loops do not keep track of index. So we can not obtain array index using For-Each loop for (int num : numbers) t if (sum = target) { return 222; // do not know the index of mm. 3 3. For-each only iterates forward over the array in single steps J} cannot be converted to a for-each loop for (int isnumbers length-1; { System out printin(mumbers(i)): } 4. For-each cannot process two decision making statements at once J! cannot be easily Converted to a for-each loop for (int i=0; i

You might also like