SlideShare a Scribd company logo
Stream
Java programs perform I/O through streams.
A stream is an abstraction that either produces or
consumes information.
A stream is linked to a physical device by the Java I/O
system.
Java defines two types of streams
1.Byte Streams
2.Character Streams
Byte streams provide a convenient means for
handling input and output of bytes.
Byte streams are used to read and write binary data.
Character streams provide a convenient means for
handling input and output of characters.
Character streams use Unicode.
Stream Classes
Stream-based I/O is built upon four abstract classes.
They are
1.InputStream:
2.OutputStream:
3.Reader:
4.Writer.
InputStream and OutputStream are designed for byte
streams.
Reader and Writer are designed for character
streams.
InputStream class
InputStream class is an abstract class. It is the
super class of all classes representing an input
stream of bytes.
methods of InputStream
InputStream class Hierarchy
OutputStream class
OutputStream class is an abstract class. It is the super
class of all classes representing an output stream of
bytes.
methods of OutputStream
OutputStream class Hierarchy
FileInputStream
FileInputStream class obtains input bytes from a file.
It is used for reading byte-oriented data such as
image data, audio, video etc.
Its constructors
FileInputStream(String filepath)
FileInputStream(File fileObj)
Example
FileInputStream f0 = new FileInputStream("abc.txt")
File f = new File(“abc.txt");
FileInputStream f1 = new FileInputStream(f);
Example
import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream(“input.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
FileOutputStream
Java FileOutputStream is an output stream used for
writing data to a file.
Its constructors
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
Example
import java.io.FileOutputStream;
public class FileOutputStreamExample
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("output.txt");
String s="Welcome to CMRCET.";
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);
}
}
}
File Operations Reading, Writing and Closing
import java.io.*;
public class CopyFile
{
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Reader class
Reader is an abstract class for reading character
streams.
The methods that a subclass must implement are
1.read(char[], int, int)
2.close().
Reader class Hierarchy
Writer class
It is an abstract class for writing to character streams.
The methods that a subclass must implement are
write(char[], int, int)
flush()
close()
Writer class Hierarchy
FileReader Class
FileReader class is used to read data from the file.
It returns data in byte format like FileInputStream class
Its constructors
FileReader(String filePath)
FileReader(File fileObj)
Example
import java.io.FileReader;
public class FileReaderExample
{
public static void main(String args[])throws Exceptio
n{
FileReader fr=new FileReader("test.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
FileWriter class
FileWriter class is used to write character-
oriented data to a file.
Its constructors
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
Methods of FileWriter class
1. void write(String text):It is used to write the string
into FileWriter.
2. void write(char c):It is used to write the char into
FileWriter.
3. void write(char[] c):It is used to write char array
into FileWriter.
4. void flush():It is used to flushes the data of
FileWriter.
5. void close():It is used to close the FileWriter.
Example
import java.io.FileWriter;
public class FileWriterExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter(“out.txt");
fw.write("Welcome to CMRCET");
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success...");
}
}
ArrayList Class
1.The underlined data structure is Resizable Array or
Grow able Array.
2.Duplicates are allowed.
3.Insertion order is preserved.
4.Heterogeneous objects are allowed.
5.Null insertion is possible.
ArrayList Constructors
1.ArrayList al = new ArrayList()
Creates an empty Array list object with default
capacity 10.
Once ArrayList reaches its max capacity a new Array
List will be created with
new capacity=(currentcapacity*3/2)+1.
2. ArrayList al = new ArrayList(int initialCapacity);
3. ArrayList al=new ArrayList(Collection c)
Example
Import java.util.*;
Class ArryListDemo
{
Pubilc static void main(String arg[])
{
ArrayList l=new ArrayList();
l.add(“a”);
l.add(10);
l.add(“a”);
l.add(null);
Sysytem.out.println(l);
l.remove(2);
System.out.println(l);
l.add(“2”,”m”);
l.add(“n”);
System.out.println(l);
}
}
Usually we can use collections to hold and transfer
Objects from on place to other place, to provide
support for this requirement every Collection
already implements Serializable and Cloneable
interfaces.
ArrayList class implements RandomAccess interface
so that we can access any Random element with
the same speed.
Hence if our frequent operation is retrieval operation
then ArrayList is the best choice.
ArrayList is the worst choice if our frequent operation
is insertion or deletion in the middle(Because
several shift operation are required).
Vector class
1. The underlying Data structure for the vcetor is
resizable array or growable arrray.
2. Duplicates are allowed.
3. Insertion order is preserved.
4. Heterogeneous objects are allowed.
5. Null insertion is possible.
6. Vector class implements Serializable, Cloneable
and RandomAccess Interfaces.
7. Most of the methods presnt in vector are
synchronized. Hence vector object is Thread–safe.
8. Best choice if the frequent operation is retrieval.
Vector specific methods
For adding objects
Add(Object o); [from Collection -List(l)]
Add(int index, Object o); [from List]
addElement(Object o) [from Vector]
For removing Objects
remove(Object o) [from Collection]
removeElement(Object o) [from Vector]
remove(int index) [from List]
removeElementAt(int index) [from Vector]
Clear() [from Collection]
removeElementAt()[from Vector]
For Accessing Elements
Object get(int index) [from Collection]
Object elementAt(int index) [from Vector]
Object firstElement() [from Vector]
Object lastElement() [from Vector]
Other Methods
int size();// currently how many objects are
there
int capacity();// total how many objects we
can accommodate.
Enumeration elements();//to get elements
one by one .
Vector class constructors
1.Vector v= new Vector();
- Create an empty vector object with default capacity
10,once vector reaches its max capacity a new vector
object will be created with new capacity=2* current
capacity.
2. Vector v= new Vector (int initialCapacity)
-creates an empty vector object with specified initial
capacity.
3.Vector v=new Vector(int initial Capacity, int
incremental Capacity)
4.Vector v=new Vector(Collection c);
- Creates an equivalent vector Object for the given
Collection
Example
Import java.util.*;
Class VectorDemo
{
public static void main(String args[])
{
Vector v=new Vector();
System.out.println(v.capacity());
for(int i=0;i<10;i++)
{
v.addElement(i);
}
System.out.println(v.capacity());
v.addElement(“A”);
System.out.println(v.capacity());
System.out.println(v);
}
}
Hashtable
1. The underlying data structure for Hashtable is Hashtable
only.
2. Insertion order is not persevered and it is based on hash
code of keys.
3. Duplicate keys are not allowed but values can be duplicated.
4. Heterogeneous objects are allowed for both keys and
values.
5. Null is not allowed for both key and value, other wise we
will get runtime exception saying null pointer exception
6. It implements Serializable and Cloneable interfaces but not
RandomAccess.
7. Every method present in hash table is synchronized and
hence hash table object is Thread-safe.
8. Hash table is best choice if our frequent operation is search
operation.
Constructors
1.Hashtable h=new Hashtable();
- default capacity is 11. and default fillRatio 0.75
2. Hashtable h=new Hashtable(int initial capacity);
3. Hashtable h=new Hashtable(int initial capacity, float
fillRatio)
4. Hashtable h=new Hashtable(map m);
fillRatio
The decision of "When to increase the number of
buckets" is decided by fillRatio (Load Factor).
If fillRatio<(m/n) then Hash table size will be doubled.
Where m=number of entries in a Hashtable
n=Total size of hashtable.
Example
Import java.util.*;
Class HashTableDemo
{
public static void main(String args[])
{
Hashtable h=new Hashtable(); //Hashtable h=new Hashtable(25);
h.put(new Temp(5), “A”);
h.put(new Temp(2), “B”);
h.put(new Temp(6), “C”);
h.put(new Temp(15), “D”);
h.put(new Temp(23), “E”);
h.put(new Temp(16), “F”);
System.out.println(h);
}
}
Class Temp
{
int i;
Temp(int i)
{
this.i=i;
}
Public int hashCode()
{
return i;// return i%9
}
public String toString()
{
return i+””;
}
}
Display order
From Top to bottom
And with in the Bucket the values are taken from right to left
Out put:
{6=C,16=F,5=A,15=D,2=B,23=E}
If Hash code changes
Out put:
{16=F,15=D,6=C,23=E,5=A,2=B}
10
9
8
7
6 6=C
5 5=A,
16=F
4 15=D
3
2 2=B
1 23=E
0
10
9
8
7 16=F
6 6=C,
15=D
5 5=A,
23=E
4
3
2 2=B
1
0
StringTokenizer class
StringTokenizer class in Java is used to break a string
into tokens.
Example
Constructors:
StringTokenizer(String str) :
str is string to be tokenized. Considers default delimiters like
new line, space, tab, carriage return and form feed.
StringTokenizer(String str, String delim) :
delim is set of delimiters that are used to tokenize the given
string.
StringTokenizer(String str, String delim, boolean flag):
The first two parameters have same meaning. The flag
serves following purpose. If the flag is false, delimiter
characters serve to separate tokens. For example, if string
is "hello geeks" and delimiter is " ", then tokens are
"hello" and “VCE". If the flag is true, delimiter characters
are considered to be tokens. For example, if string is
"hello VCE" and delimiter is " ", then tokens are "hello", "
" and “VCE".
Methods
boolean hasMoreTokens():checks if there is more
tokens available.
String nextToken():returns the next token from the
StringTokenizer object.
String nextToken(String delim):returns the next
token based on the delimeter.
boolean hasMoreElements(): same as
hasMoreTokens() method.
Object nextElement(): same as nextToken() but its
return type is Object.
int countTokens():returns the total number of tokens.
Example
import java.util.*;
public class NewClass
{
public static void main(String args[])
{
System.out.println("Using Constructor 1 - ");
StringTokenizer st1 = new StringTokenizer("Hello vce How are you", " ");
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("Using Constructor 2 - ");
StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :");
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
System.out.println("Using Constructor 3 - ");
StringTokenizer st3 =new StringTokenizer("JAVA : Code : String", " :", true);
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
Date class
• The java.util.Date class represents date and
time in java. It provides constructors and
methods to deal with date and time in java.
• The java.util.Date class implements
Serializable, Cloneable and
Comparable<Date> interface. It is inherited by
java.sql.Date, java.sql.Time and
java.sql.Timestamp interfaces.
Constructors
1.Date():Creates a date object representing
current date and time.
2.Date(long milliseconds):Creates a date object
for the given milliseconds since January 1,
1970, 00:00:00 GMT.
Methods
1)boolean after(Date date): tests if current date is after the given
date.
2)boolean before(Date date):tests if current date is before the given
date.
3)Object clone():returns the clone object of current date.
4)int compareTo(Date date):compares current date with given date.
5)boolean equals(Date date):compares current date with given date
for equality.
6)static Date from(Instant instant):returns an instance of Date
object from Instant date.
7)long getTime():returns the time represented by this date object.
8)int hashCode():returns the hash code value for this date object.
9)void setTime(long time):changes the current date and time to
given time.
10)Instant toInstant():converts current date into Instant object.
11)String toString():converts this date into Instant object.
Example
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Date d1 = new Date();
System.out.println("Current date is " + d1);
Date d2 = new Date(2323223232L);
System.out.println("Date represented is "+ d2 );
}
}
Out put
Current date is Sat Oct 07 04:14:42 IST 2017
Date represented is Wed Jan 28 02:50:23 IST 1970
Ad

Recommended

Java Day-6
Java Day-6
People Strategists
 
Input/Output Exploring java.io
Input/Output Exploring java.io
NilaNila16
 
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
11_Str11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.11_Streams.eams.pdf
hungvidien123
 
IOStream.pptx
IOStream.pptx
HindAlmisbahi
 
Java I/O
Java I/O
Jayant Dalvi
 
Programming language JAVA Input output opearations
Programming language JAVA Input output opearations
2025183005
 
Input & output
Input & output
SAIFUR RAHMAN
 
Input output files in java
Input output files in java
Kavitha713564
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
File Input and output.pptx
File Input and output.pptx
cherryreddygannu
 
Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
Java Basics
Java Basics
shivamgarg_nitj
 
Java Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Files & IO in Java
Files & IO in Java
CIB Egypt
 
05io
05io
Waheed Warraich
 
Java IO
Java IO
UTSAB NEUPANE
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
FileHandling.docx
FileHandling.docx
NavneetSheoran3
 
File Handling.pptx
File Handling.pptx
PragatiSutar4
 
Java class 5
Java class 5
Edureka!
 
Java stream
Java stream
Arati Gadgil
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
File Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Jstreams
Jstreams
Shehrevar Davierwala
 
EventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 

More Related Content

Similar to file handling in object oriented programming through java (20)

chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
File Input and output.pptx
File Input and output.pptx
cherryreddygannu
 
Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
Java Basics
Java Basics
shivamgarg_nitj
 
Java Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Files & IO in Java
Files & IO in Java
CIB Egypt
 
05io
05io
Waheed Warraich
 
Java IO
Java IO
UTSAB NEUPANE
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
FileHandling.docx
FileHandling.docx
NavneetSheoran3
 
File Handling.pptx
File Handling.pptx
PragatiSutar4
 
Java class 5
Java class 5
Edureka!
 
Java stream
Java stream
Arati Gadgil
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
File Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 
Jstreams
Jstreams
Shehrevar Davierwala
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
Monhocvecaujahetvagiuplaptunhhayhonha.pdf
cuchuoi83ne
 
File Input and output.pptx
File Input and output.pptx
cherryreddygannu
 
Java căn bản - Chapter12
Java căn bản - Chapter12
Vince Vo
 
Chapter 12 - File Input and Output
Chapter 12 - File Input and Output
Eduardo Bergavera
 
9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Java IO Stream, the introduction to Streams
Java IO Stream, the introduction to Streams
ranganadh6
 
Java Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Files & IO in Java
Files & IO in Java
CIB Egypt
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
Java class 5
Java class 5
Edureka!
 
IO Programming.pptx all informatiyon ppt
IO Programming.pptx all informatiyon ppt
nandinimakwana22cse
 
File Handling in Java.pdf
File Handling in Java.pdf
SudhanshiBakre1
 

More from Parameshwar Maddela (11)

EventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
working with interfaces in java programming
working with interfaces in java programming
Parameshwar Maddela
 
introduction to object orinted programming through java
introduction to object orinted programming through java
Parameshwar Maddela
 
multhi threading concept in oops through java
multhi threading concept in oops through java
Parameshwar Maddela
 
Object oriented programming -QuestionBank
Object oriented programming -QuestionBank
Parameshwar Maddela
 
22H51A6755.pptx
22H51A6755.pptx
Parameshwar Maddela
 
swings.pptx
swings.pptx
Parameshwar Maddela
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
02_Data Types in java.pdf
02_Data Types in java.pdf
Parameshwar Maddela
 
Intro tooop
Intro tooop
Parameshwar Maddela
 
EventHandling in object oriented programming
EventHandling in object oriented programming
Parameshwar Maddela
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
working with interfaces in java programming
working with interfaces in java programming
Parameshwar Maddela
 
introduction to object orinted programming through java
introduction to object orinted programming through java
Parameshwar Maddela
 
multhi threading concept in oops through java
multhi threading concept in oops through java
Parameshwar Maddela
 
Object oriented programming -QuestionBank
Object oriented programming -QuestionBank
Parameshwar Maddela
 
03_Objects and Classes in java.pdf
03_Objects and Classes in java.pdf
Parameshwar Maddela
 
Ad

Recently uploaded (20)

How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
RAKESH SAJJAN
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Measuring, learning and applying multiplication facts.
Measuring, learning and applying multiplication facts.
cgilmore6
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
JHS SHS Back to School 2024-2025 .pptx
JHS SHS Back to School 2024-2025 .pptx
melvinapay78
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
Non-Communicable Diseases and National Health Programs – Unit 10 | B.Sc Nursi...
RAKESH SAJJAN
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Measuring, learning and applying multiplication facts.
Measuring, learning and applying multiplication facts.
cgilmore6
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
JHS SHS Back to School 2024-2025 .pptx
JHS SHS Back to School 2024-2025 .pptx
melvinapay78
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
Assisting Individuals and Families to Promote and Maintain Health – Unit 7 | ...
RAKESH SAJJAN
 
Ad

file handling in object oriented programming through java

  • 1. Stream Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. Java defines two types of streams 1.Byte Streams 2.Character Streams
  • 2. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used to read and write binary data. Character streams provide a convenient means for handling input and output of characters. Character streams use Unicode.
  • 3. Stream Classes Stream-based I/O is built upon four abstract classes. They are 1.InputStream: 2.OutputStream: 3.Reader: 4.Writer. InputStream and OutputStream are designed for byte streams. Reader and Writer are designed for character streams.
  • 4. InputStream class InputStream class is an abstract class. It is the super class of all classes representing an input stream of bytes. methods of InputStream
  • 6. OutputStream class OutputStream class is an abstract class. It is the super class of all classes representing an output stream of bytes. methods of OutputStream
  • 8. FileInputStream FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data such as image data, audio, video etc. Its constructors FileInputStream(String filepath) FileInputStream(File fileObj) Example FileInputStream f0 = new FileInputStream("abc.txt") File f = new File(“abc.txt"); FileInputStream f1 = new FileInputStream(f);
  • 9. Example import java.io.FileInputStream; public class DataStreamExample { public static void main(String args[]) { try { FileInputStream fin=new FileInputStream(“input.txt"); int i=0; while((i=fin.read())!=-1) { System.out.print((char)i); } fin.close(); } catch(Exception e) { System.out.println(e); } } }
  • 10. FileOutputStream Java FileOutputStream is an output stream used for writing data to a file. Its constructors FileOutputStream(String filePath) FileOutputStream(File fileObj) FileOutputStream(String filePath, boolean append) FileOutputStream(File fileObj, boolean append)
  • 11. Example import java.io.FileOutputStream; public class FileOutputStreamExample { public static void main(String args[]) { try { FileOutputStream fout=new FileOutputStream("output.txt"); String s="Welcome to CMRCET."; 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. File Operations Reading, Writing and Closing import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
  • 13. Reader class Reader is an abstract class for reading character streams. The methods that a subclass must implement are 1.read(char[], int, int) 2.close().
  • 15. Writer class It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int) flush() close()
  • 17. FileReader Class FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class Its constructors FileReader(String filePath) FileReader(File fileObj)
  • 18. Example import java.io.FileReader; public class FileReaderExample { public static void main(String args[])throws Exceptio n{ FileReader fr=new FileReader("test.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close(); } }
  • 19. FileWriter class FileWriter class is used to write character- oriented data to a file. Its constructors FileWriter(String filePath) FileWriter(String filePath, boolean append) FileWriter(File fileObj) FileWriter(File fileObj, boolean append)
  • 20. Methods of FileWriter class 1. void write(String text):It is used to write the string into FileWriter. 2. void write(char c):It is used to write the char into FileWriter. 3. void write(char[] c):It is used to write char array into FileWriter. 4. void flush():It is used to flushes the data of FileWriter. 5. void close():It is used to close the FileWriter.
  • 21. Example import java.io.FileWriter; public class FileWriterExample { public static void main(String args[]) { try { FileWriter fw=new FileWriter(“out.txt"); fw.write("Welcome to CMRCET"); fw.close(); } catch(Exception e) { System.out.println(e); } System.out.println("Success..."); } }
  • 22. ArrayList Class 1.The underlined data structure is Resizable Array or Grow able Array. 2.Duplicates are allowed. 3.Insertion order is preserved. 4.Heterogeneous objects are allowed. 5.Null insertion is possible.
  • 23. ArrayList Constructors 1.ArrayList al = new ArrayList() Creates an empty Array list object with default capacity 10. Once ArrayList reaches its max capacity a new Array List will be created with new capacity=(currentcapacity*3/2)+1.
  • 24. 2. ArrayList al = new ArrayList(int initialCapacity); 3. ArrayList al=new ArrayList(Collection c)
  • 25. Example Import java.util.*; Class ArryListDemo { Pubilc static void main(String arg[]) { ArrayList l=new ArrayList(); l.add(“a”); l.add(10); l.add(“a”); l.add(null); Sysytem.out.println(l); l.remove(2); System.out.println(l); l.add(“2”,”m”); l.add(“n”); System.out.println(l); } }
  • 26. Usually we can use collections to hold and transfer Objects from on place to other place, to provide support for this requirement every Collection already implements Serializable and Cloneable interfaces. ArrayList class implements RandomAccess interface so that we can access any Random element with the same speed. Hence if our frequent operation is retrieval operation then ArrayList is the best choice. ArrayList is the worst choice if our frequent operation is insertion or deletion in the middle(Because several shift operation are required).
  • 27. Vector class 1. The underlying Data structure for the vcetor is resizable array or growable arrray. 2. Duplicates are allowed. 3. Insertion order is preserved. 4. Heterogeneous objects are allowed. 5. Null insertion is possible. 6. Vector class implements Serializable, Cloneable and RandomAccess Interfaces. 7. Most of the methods presnt in vector are synchronized. Hence vector object is Thread–safe. 8. Best choice if the frequent operation is retrieval.
  • 28. Vector specific methods For adding objects Add(Object o); [from Collection -List(l)] Add(int index, Object o); [from List] addElement(Object o) [from Vector] For removing Objects remove(Object o) [from Collection] removeElement(Object o) [from Vector] remove(int index) [from List] removeElementAt(int index) [from Vector] Clear() [from Collection] removeElementAt()[from Vector]
  • 29. For Accessing Elements Object get(int index) [from Collection] Object elementAt(int index) [from Vector] Object firstElement() [from Vector] Object lastElement() [from Vector] Other Methods int size();// currently how many objects are there int capacity();// total how many objects we can accommodate. Enumeration elements();//to get elements one by one .
  • 30. Vector class constructors 1.Vector v= new Vector(); - Create an empty vector object with default capacity 10,once vector reaches its max capacity a new vector object will be created with new capacity=2* current capacity. 2. Vector v= new Vector (int initialCapacity) -creates an empty vector object with specified initial capacity. 3.Vector v=new Vector(int initial Capacity, int incremental Capacity) 4.Vector v=new Vector(Collection c); - Creates an equivalent vector Object for the given Collection
  • 31. Example Import java.util.*; Class VectorDemo { public static void main(String args[]) { Vector v=new Vector(); System.out.println(v.capacity()); for(int i=0;i<10;i++) { v.addElement(i); } System.out.println(v.capacity()); v.addElement(“A”); System.out.println(v.capacity()); System.out.println(v); } }
  • 32. Hashtable 1. The underlying data structure for Hashtable is Hashtable only. 2. Insertion order is not persevered and it is based on hash code of keys. 3. Duplicate keys are not allowed but values can be duplicated. 4. Heterogeneous objects are allowed for both keys and values. 5. Null is not allowed for both key and value, other wise we will get runtime exception saying null pointer exception 6. It implements Serializable and Cloneable interfaces but not RandomAccess. 7. Every method present in hash table is synchronized and hence hash table object is Thread-safe. 8. Hash table is best choice if our frequent operation is search operation.
  • 33. Constructors 1.Hashtable h=new Hashtable(); - default capacity is 11. and default fillRatio 0.75 2. Hashtable h=new Hashtable(int initial capacity); 3. Hashtable h=new Hashtable(int initial capacity, float fillRatio) 4. Hashtable h=new Hashtable(map m); fillRatio The decision of "When to increase the number of buckets" is decided by fillRatio (Load Factor). If fillRatio<(m/n) then Hash table size will be doubled. Where m=number of entries in a Hashtable n=Total size of hashtable.
  • 34. Example Import java.util.*; Class HashTableDemo { public static void main(String args[]) { Hashtable h=new Hashtable(); //Hashtable h=new Hashtable(25); h.put(new Temp(5), “A”); h.put(new Temp(2), “B”); h.put(new Temp(6), “C”); h.put(new Temp(15), “D”); h.put(new Temp(23), “E”); h.put(new Temp(16), “F”); System.out.println(h); } }
  • 35. Class Temp { int i; Temp(int i) { this.i=i; } Public int hashCode() { return i;// return i%9 } public String toString() { return i+””; } }
  • 36. Display order From Top to bottom And with in the Bucket the values are taken from right to left Out put: {6=C,16=F,5=A,15=D,2=B,23=E} If Hash code changes Out put: {16=F,15=D,6=C,23=E,5=A,2=B} 10 9 8 7 6 6=C 5 5=A, 16=F 4 15=D 3 2 2=B 1 23=E 0 10 9 8 7 16=F 6 6=C, 15=D 5 5=A, 23=E 4 3 2 2=B 1 0
  • 37. StringTokenizer class StringTokenizer class in Java is used to break a string into tokens. Example
  • 38. Constructors: StringTokenizer(String str) : str is string to be tokenized. Considers default delimiters like new line, space, tab, carriage return and form feed. StringTokenizer(String str, String delim) : delim is set of delimiters that are used to tokenize the given string. StringTokenizer(String str, String delim, boolean flag): The first two parameters have same meaning. The flag serves following purpose. If the flag is false, delimiter characters serve to separate tokens. For example, if string is "hello geeks" and delimiter is " ", then tokens are "hello" and “VCE". If the flag is true, delimiter characters are considered to be tokens. For example, if string is "hello VCE" and delimiter is " ", then tokens are "hello", " " and “VCE".
  • 39. Methods boolean hasMoreTokens():checks if there is more tokens available. String nextToken():returns the next token from the StringTokenizer object. String nextToken(String delim):returns the next token based on the delimeter. boolean hasMoreElements(): same as hasMoreTokens() method. Object nextElement(): same as nextToken() but its return type is Object. int countTokens():returns the total number of tokens.
  • 40. Example import java.util.*; public class NewClass { public static void main(String args[]) { System.out.println("Using Constructor 1 - "); StringTokenizer st1 = new StringTokenizer("Hello vce How are you", " "); while (st1.hasMoreTokens()) System.out.println(st1.nextToken()); System.out.println("Using Constructor 2 - "); StringTokenizer st2 = new StringTokenizer("JAVA : Code : String", " :"); while (st2.hasMoreTokens()) System.out.println(st2.nextToken()); System.out.println("Using Constructor 3 - "); StringTokenizer st3 =new StringTokenizer("JAVA : Code : String", " :", true); while (st3.hasMoreTokens()) System.out.println(st3.nextToken()); } }
  • 41. Date class • The java.util.Date class represents date and time in java. It provides constructors and methods to deal with date and time in java. • The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.
  • 42. Constructors 1.Date():Creates a date object representing current date and time. 2.Date(long milliseconds):Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
  • 43. Methods 1)boolean after(Date date): tests if current date is after the given date. 2)boolean before(Date date):tests if current date is before the given date. 3)Object clone():returns the clone object of current date. 4)int compareTo(Date date):compares current date with given date. 5)boolean equals(Date date):compares current date with given date for equality. 6)static Date from(Instant instant):returns an instance of Date object from Instant date. 7)long getTime():returns the time represented by this date object. 8)int hashCode():returns the hash code value for this date object. 9)void setTime(long time):changes the current date and time to given time. 10)Instant toInstant():converts current date into Instant object. 11)String toString():converts this date into Instant object.
  • 44. Example import java.util.*; public class Main { public static void main(String[] args) { Date d1 = new Date(); System.out.println("Current date is " + d1); Date d2 = new Date(2323223232L); System.out.println("Date represented is "+ d2 ); } } Out put Current date is Sat Oct 07 04:14:42 IST 2017 Date represented is Wed Jan 28 02:50:23 IST 1970