Presentation is loading. Please wait.

Presentation is loading. Please wait.

File I/O & collection frame work

Similar presentations


Presentation on theme: "File I/O & collection frame work"— Presentation transcript:

1 File I/O & collection frame work

2 File Classes The File class in the Java IO API gives you access to the underlying file system. Using the File class you can: Check if a file or directory exists. Create a directory if it does not exist. Read the length of a file. Rename or move a file. Delete a file. Check if path is file or directory. Read list of files in a directory.

3 Before you can do anything with the file system or File class, you must obtain a File instance.
File file = new File("c:\\data\\input-file.txt"); Check if File Exists boolean fileExists = file.exists(); Create a Directory if it Does Not Exist File file = new File("c:\\users\\java\\newdir"); boolean dirCreated = file.mkdir();

4 File file = new File("c:\\data\\input-file.txt");
File Length File file = new File("c:\\data\\input-file.txt"); long length = file.length(); Rename or Move File boolean success = file.renameTo(new File("c:\\new-file.txt")); Delete File boolean success = file.delete();

5 Stream Classes Stream Classes
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. A stream means continuous flow of data.

6 Java defines two types of streams.
Byte Stream : It provides a convenient means for handling input and output of byte. Character Stream : It provides a convenient means for handling input and output of characters. Character stream uses Unicode and therefore can be internationalized.

7 Byte Stream Classes Byte stream is defined by using two abstract class at the top of hierarchy, they are InputStream and OutputStream. These two abstract classes have several concrete classes that handle various devices such as disk files, network connection etc.

8 Some important Byte stream classes
Description BufferedInputStream Used for Buffered Input Stream. BufferedOutputStream Used for Buffered Output Stream. DataInputStream Contains method for reading java standard data type DataOutputStream An output stream that contain method for writing java standard data type FileInputStream Input stream that reads from a file FileOutputStream Output stream that write to a file. InputStream Abstract class that describe stream input. OutputStream Abstract class that describe stream output. PrintStream Output Stream that contain print() and println() method

9 These classes define several key methods. Two most important are:
read() : reads byte of data. write() : Writes byte of data.

10 FileOutputStream class
The Java.io.FileOutputStream class is an output stream for writing data to a File or to a FileDescriptor. FileOutputStream class is meant for writing streams of raw bytes such as image data.

11 import java.io.*; class Test { public static void main(String args[]) try FileOutputstream fout=new FileOutputStream("abc.txt"); String s=“Marathwada Mitra Mandal’s Polytechnic."; byte b[]=s.getBytes(); //converting string into byte array fout.write(b); fout.close(); System.out.println("success..."); } catch(Exception e) { system.out.println(e); } }

12 FileInputStream The Java.io.FileInputStream class obtains input bytes from a file in a file system. FileInputStream class is meant for reading streams of raw bytes such as image data.

13 import java.io.*;   class SimpleRead {    public static void main(String args[])   try     FileInputStream fin=new FileInputStream("abc.txt");       int i=0;       while((i=fin.read())!=-1)      System.out.println((char)i);       }       fin.close();     } catch(Exception e) { system.out.println(e); }    }  

14 Character Stream Classes
Character stream is also defined by using two abstract class at the top of hierarchy, they are Reader and Writer. These two abstract classes have several concrete classes that handle unicode character.

15 Some important Character stream classes.
Description BufferedReader Handles buffered input stream. BufferedWriter Handles buffered output stream. FileReader Input stream that reads from file. FileWriter Output stream that writes to file. InputStreamReader Input stream that translate byte to character OutputStreamReader Output stream that translate character to byte. PrintWriter Output Stream that contain print() and println() method. Reader Abstract class that define character stream input Writer Abstract class that define character stream output

16 FileWriter class FileWriter class is used to write character-oriented data to the file. Constructors of FileWriter class Constructor Description FileWriter(String file) creates a new file. It gets file name in string. FileWriter(File file) creates a new file. It gets file name in File object.

17 Methods of FileWriter class
Description 1) public void write(String text) writes the string into FileWriter. 2) public void write(char c) writes the char into FileWriter. 3) public void write(char[] c) writes char array into FileWriter. 4) public void flush() flushes the data of FileWriter. 5) public void close() closes FileWriter.

18 import java.io.*; class Simple { public static void main(String args[]) try FileWriter fw=new FileWriter("abc.txt"); fw.write(“M.M.Polytechnic"); fw.close(); } catch(Exception e) { System.out.println(e);} System.out.println("success"); } }

19 FileReader class Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class. Constructors of FileWriter class Constructor Description FileReader(String file) It gets filename in string. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException. FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file doesn't exist, it throws FileNotFoundException.

20 Methods of FileReader class
Description 1) public int read() returns a character in ASCII form. It returns -1 at the end of file. 2) public void close() closes FileReader.

21 import java.io.*; class Simple { public static void main(String args[])throws Exception FileReader fr=new FileReader("abc.txt"); int i; while((i=fr.read())!=-1) System.out.println((char)i); fr.close(); } }

22 Serialization and Deserialization
Serialization is a process of converting an object into a sequence of bytes which can be written to a disk or database or can be sent through streams. Serialized object includes the object's data as well as information about the object's type and the types of data stored in the object. The reverse process of creating object from sequence of bytes is called deserialization. A class must implement Serializable interface present in java.io package in order to serialize its object successfully. 

23 Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object. The writeObject() method of ObjectOutputStream class is used to serialize an Object. The readObject() method of ObjectInputStream class is used to deserialize an Object.

24 Collections frame work
The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy.

25 ArrayList al=new ArrayList();
Java ArrayList class uses a dynamic array for storing the elements. It extends AbstractList class and implements List interface. Java ArrayList class can contain duplicate elements. Java ArrayList class maintains insertion order. Java ArrayList allows random access because array works at the index basis. In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list. ArrayList al=new ArrayList();

26 Methods of Array list Method Description
void add(int index, Object element) Inserts the specified element at the specified position index in this list. void clear() Removes all of the elements from this list. boolean contains(Object o) Returns true if this list contains the specified element. int indexOf(Object o) Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. int lastIndexOf(Object o) Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. Object remove(int index) Removes the element at the specified position in this list. Object get(int index) Returns the element at the specified position in this list. 

27 Date Class Java provides the Date class available in java.util package. It provides constructors and methods to deal with date and time in java. Constructors Constructor Description Date() Creates a date object representing current date and time. Date(long milliseconds) Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.

28 Methods Date Class Method Description boolean after(Date date)
tests if current date is after the given date. boolean before(Date date) tests if current date is before the given date. Object clone() returns the clone object of current date. int compareTo(Date date) compares current date with given date. boolean equals(Date date) compares current date with given date for equality. long getTime() returns the time represented by this date object. public int getDay() Returns the day of the week represented by this date. The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the week. void setTime(long time) changes the current date and time to given time. public int getDate() Returns the day of the month represented by this Date object. The value returned is between 1 and 31 representing the day of the month

29 set Interface The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. It models the mathematical set abstraction.

30 Methods Set Interface Method Description add( )
Adds an object to the collection. clear( ) Removes all objects from the collection. contains( ) Returns true if a specified object is an element within the collection. isEmpty( ) Returns true if the collection has no elements. iterator( ) Returns an Iterator object for the collection, which may be used to retrieve an object. remove( ) Removes a specified object from the collection. size( ) Returns the number of elements in the collection.

31 Iterator Interface Iterator is used various collection classes. Both Iterator and ListIterator are used for iterating (looping) through elements of a collection classes such as HashMap, ArrayList, LinkedList etc. Using Iterator we can traverse in one direction (forward) while using ListIterator we can traverse the collection class on both the directions(backward and forward).

32 Methods Iterator Interface
Description boolean hasNext() Returns true if the iteration has more elements.  Object next() Returns the next element in the iteration.  void remove() Removes from the underlying collection the last element returned by the iterator (optional operation).

33 map Interface The map interface describes a mapping from keys to values i.e. key and value pair. Each key and value pair is known as an entry. Map contains only unique keys. Map is useful if you have to search, update or delete elements on the basis of key.

34 Methods of map Interface
Description public Object put(Object key, Object value) is used to insert an entry in this map. public void putAll(Map map) is used to insert the specified map in this map. public Object remove(Object key) is used to delete an entry for the specified key. public Object get(Object key) is used to return the value for the specified key. public boolean containsKey(Object key) is used to search the specified key from this map. public Set keySet() returns the Set view containing all the keys. public Set entrySet() returns the Set view containing all the keys and values.


Download ppt "File I/O & collection frame work"

Similar presentations


Ads by Google