You are on page 1of 34

File I/O & collection frame work

Mrs. Chavan P.P.


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.

Mrs. Chavan P.P.


• 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


File file = new File("c:\\data\\input-file.txt");
boolean fileExists = file.exists();

• Create a Directory if it Does Not Exist


File file = new File("c:\\users\\java\\newdir");
boolean dirCreated = file.mkdir();
Mrs. Chavan P.P.
• File Length
File file = new File("c:\\data\\input-file.txt");
long length = file.length();

• Rename or Move File


File file = new File("c:\\data\\input-file.txt");
boolean success = file.renameTo(new File("c:\\new-file.txt"));

• Delete File
File file = new File("c:\\data\\input-file.txt");
boolean success = file.delete();
Mrs. Chavan P.P.
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.

Mrs. Chavan P.P.


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.

Mrs. Chavan P.P.


• 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.
Mrs. Chavan P.P.
• Some important Byte stream classes
Stream class 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 Mrs. Chavan P.P.
These classes define several key methods. Two
most important are:

• read() : reads byte of data.


• write() : Writes byte of data.

Mrs. Chavan P.P.


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.

Mrs. Chavan P.P.


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);
}
}
Mrs. Chavan P.P.
}
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.

Mrs. Chavan P.P.


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);
}
}
} Mrs. Chavan P.P.
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.
Mrs. Chavan P.P.
• Some important Character stream classes.
Stream class 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.


Output Stream that contain print() and println()
PrintWriter
method.
Reader Abstract class that define character stream input

Writer Abstract class that define character stream output


Mrs. Chavan P.P.
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.

Mrs. Chavan P.P.


Methods of FileWriter class
Method 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.

Mrs. Chavan P.P.


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");
}
}
Mrs. Chavan P.P.
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

It gets filename in string. It opens the given file in read


FileReader(String file) mode. If file doesn't exist, it throws
FileNotFoundException.

It gets filename in file instance. It opens the given file in


FileReader(File file) read mode. If file doesn't exist, it throws
FileNotFoundException.
Mrs. Chavan P.P.
Methods of FileReader class
Method Description

returns a character in ASCII form. It returns -1 at the


1) public int read()
end of file.

2) public void close() closes FileReader.

Mrs. Chavan P.P.


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();
}
}

Mrs. Chavan P.P.


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.
Mrs. Chavan P.P.
• Classes ObjectInputStream and ObjectOutput
Stream 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.

Mrs. Chavan P.P.


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.

Mrs. Chavan P.P.


Array list
• 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
Mrs. Chavan P.P.
ArrayList();
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.
Mrs. Chavan P.P.
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.
Mrs. Chavan P.P.
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.
Returns the day of the week represented by this date.
The returned value (0 = Sunday, 1 = Monday, 2 =
public int getDay()
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.
Returns the day of the month represented by
public int getDate() this Date object. The value returned is
betweenMrs.
1 and
Chavan31
P.P. representing the day of the month
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.

Mrs. Chavan P.P.


Methods Set Interface

Method Description
add( ) Adds an object to the collection.

clear( ) Removes all objects from the collection.

Returns true if a specified object is an element


contains( )
within the collection.

isEmpty( ) Returns true if the collection has no elements.

Returns an Iterator object for the collection, which


iterator( )
may be used to retrieve an object.

remove( ) Removes a specified object from the collection.

size( ) Returns the number of elements in the collection.


Mrs. Chavan P.P.
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).

Mrs. Chavan P.P.


Methods Iterator Interface

Method Description

boolean hasNext() Returns true if the iteration has more elements.

Object next() Returns the next element in the iteration.

Removes from the underlying collection the last element


void remove()
returned by the iterator (optional operation).

Mrs. Chavan P.P.


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.

Mrs. Chavan P.P.


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

You might also like