Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

CSE1007-JAVA Programming - Module 4

The document discusses Java I/O streams and file handling in Java. It covers topics like FileInputStream, FileOutputStream, FileReader, FileWriter and how they can be used to read from and write to files. It also provides examples of reading and writing to text files and storing student records in a file.

Uploaded by

Jeel Mehta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

CSE1007-JAVA Programming - Module 4

The document discusses Java I/O streams and file handling in Java. It covers topics like FileInputStream, FileOutputStream, FileReader, FileWriter and how they can be used to read from and write to files. It also provides examples of reading and writing to text files and storing student records in a file.

Uploaded by

Jeel Mehta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

Topic to be covered

 Data structures:
 Java I/O streams
 Working with files
 Serialization and deserialization of objects
 Lambda expressions
 Collection framework
 List, Map, Set
 Generics Annotations
Files
 Secondary Storage Device
 Persistent Data – remains after program terminates
 File (Java) – Stream of Bytes
 End of File
streams
Java I/O
 Java I/O (Input and Output) is used to process the
input and produce the output.
 Java uses the concept of a stream to make I/O
operation fast.
 The java.io package contains all the classes required
for input and output operations.
 file handling in Java is performed by Java I/O API.
Streams
 A stream is a sequence of data. In Java, a stream
is composed of bytes. It's called a stream because
it is like a stream of water that continues to flow.
 Byte Stream
 Handle input and output of bytes
 Sequence of bytes
 Ex: 5  binary format - 0101
 Character Stream
 Handle input and output of characters
 Unicode - Internationalized
 Sequence of characters
 Types of Files
 Binary File
 Text File
Standard Streams
 Java can open a file by creating an object
 Constructor interacts with OS to open the file
 3 Standard Stream objects associated with device
 System.in  Input bytes from keyboard
 System.out  Output character data to screen
 System.err  Output error message to screen
Example :
System.out.println("simple message");
System.err.println("error message");

int i=System.in.read();
//returns ASCII code of 1st character
System.out.println((char)i);
//will print the character
Byte Stream Classes
Character Stream Classes
Hierarchy of classes In Streams
java.io (package) – File Processing
 Stream classes
 FileInputStream (byte-based i/p from a file)
 FileOutputStream (byte-based o/p to a file)
 FileReader (char-based i/p from a file)
 FileWriter (char-based o/p to a file)
 Inherits from
 InputStream
 OutputStream
 Reader
 Writer
 Objects
 ObjectInputStream
 ObjectOutputStream
 Character-based Stream
 Scanner (i/p data from keyboard / file)
Streams

Source: mygreatlearning.com
FileOutputStream
 FileOutputStream is used to create a file and write data
into it. The stream would create a file, if it doesn't
already exist, before opening it for output.
 Here are two constructors which can be used to create
a FileOutputStream object.
 Following constructor takes a file name as a string to
create an input stream object to write the file −
OutputStream f = new
FileOutputStream(“D:\\Sample.txt")
 Following constructor takes a file object to create an
output stream object to write the file.
File f = new File(" D:\\Sample.txt ");
OutputStream f = new FileOutputStream(f);
Helper methods
Sr.N Method & Description
o.

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system
resources associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the
close method of this file output stream is called when there are no
more references to this stream. Throws an IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes w.length bytes from the mentioned byte array to the
OutputStream.
File output stream(Bytes)
File output stream(Streams)
BufferedOutputStream
FileInputStream
 This stream is used for reading data from the files.
Objects can be created using the keyword new and
there are several types of constructors available.
 Following constructor takes a file name as a string to
create an input stream object to read the file −
InputStream f = new FileInputStream ("C:/java/hello");
 Following constructor takes a file object to create an
input stream object to read the file.
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
Helper Methods
Sr. Method & Description
No.
1 public void close() throws IOException{}
This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.
2 protected void finalize()throws IOException {}
This method cleans up the connection to the file. Ensures that the close method
of this file output stream is called when there are no more references to this
stream. Throws an IOException.
3 public int read(int r)throws IOException{}
This method reads the specified byte of data from the InputStream. Returns an
int. Returns the next byte of data and -1 will be returned if it's the end of the file.

4 public int read(byte[] r) throws IOException{}


This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If it is the end of the file, -1 will be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream. Returns an
File input stream
File (class)
 Retrieve information about File / Directory
 Can open the file or manipulate the file using this
object
 4 Constructors
 File (String file name / directory name)
 File (String path name (absolute / relative path), String
file/dir)
 File (File object, String parent dir / dir)
 File (URI object)
 URI – Uniform Resource Identifier – general form of URL
 URI – locating files – vary with OS
 file://C:/data.txt  windows
 file:/home/student/data.txt  UNIX/Linux
File / Directory Information Access
• getName()
• isFile()
• isAbsolute()
• lastModified()
• length()
• getPath()
• getAbsolutePath()
• getParent()
File / Directory Information Access
File / Directory Information Access
Enter file or directory name: d:\\sample.txt
sample.txt exists
is a file
is absolute path
Last modified: 1647421972491
Length: 94
Path: d:\sample.txt
Absolute path: d:\sample.txt
Parent: d:\
Reading data from a file using FileReader
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
class ReadFile
{
public static void main(String[] args) throws IOException
{
int ch;
FileReader fr=null;
try{
fr = new FileReader("text"); }
catch (FileNotFoundException e){
System.out.println("File not found"); }
while ((ch=fr.read())!=-1) // read from FileReader till the end of file
System.out.print((char)ch);
fr.close();
}
}
Writing data in a file using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class CreateFile
{
public static void main(String[] args) throws IOException
{
String str = "File Handling in Java using FileWriter ";
FileWriter fw=new FileWriter("output.txt");
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));
System.out.println("Writing successful");
fw.close();
}
}
Example To store student details in
aimport
text file
java.io.*;
class StudentRecords
{
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

public void addRecords() throws IOException


{
// Create or Modify a file for Database
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("studentRecords.txt",true)));
String name, Class, fname, mname, address, dob;
int age;
long telephoneNo;
String s;
boolean addMore = false;
// Read Data
do {
System.out.print("\nEnter name: ");
name = br.readLine();

System.out.print("Father's Name: ");


fname = br.readLine();

System.out.print("Mother's Name: ");


mname = br.readLine();

System.out.print("Address: ");
address = br.readLine();

System.out.print("Class: ");
Class = br.readLine();

System.out.print("Date of Birth (dd/mm/yy) : ");


dob = br.readLine();

System.out.print("Age: ");
age = Integer.parseInt(br.readLine());

System.out.print("Telephone No.: ");


telephoneNo = Long.parseLong(br.readLine());
// Print to File
pw.println(name);
pw.println(fname);
pw.println(mname);
pw.println(address);
pw.println(Class);
pw.println(dob);
pw.println(age);
pw.println(telephoneNo);

System.out.print("\nRecords added successfully !\n\nDo you want to add


more records ? (y/n) : ");
s = br.readLine();
if(s.equalsIgnoreCase("y"))
{
addMore = true;
System.out.println();
}
else
addMore = false;
}
while(addMore);
pw.close();
showMenu();
}
public void readRecords() throws IOException
{
try
{
// Open the file
BufferedReader file = new BufferedReader(new
FileReader("studentRecords.txt"));
String name;
int i=1;
// Read records from the file
while((name = file.readLine()) != null)
{
System.out.println("S.No. : " +(i++));
System.out.println("-------------");
System.out.println("\nName: " +file.readLine());
System.out.println("Father's Name : "+file.readLine());
System.out.println("Mother's Name : "+file.readLine());
System.out.println("Address: "+file.readLine());
System.out.println("Class: "+file.readLine());
System.out.println("Date of Birth : "+file.readLine());
System.out.println("Age: "+Integer.parseInt(file.readLine()));
System.out.println("Tel. No.: "+Long.parseLong(file.readLine()));
System.out.println();
}
file.close();
showMenu();
}
catch(FileNotFoundException e)
{
System.out.println("\nERROR : File not Found !!!");
}
}
public void clear() throws IOException
{
// Create a blank file
PrintWriter pw = new PrintWriter(new BufferedWriter(new
FileWriter("studentRecords.txt")));
pw.close();
System.out.println("\nAll Records cleared successfully !");
for(int i=0;i<999999999;i++);
// Wait for some time
showMenu();
}
public void showMenu() throws IOException
{
System.out.print("1 : Add Records\n2 : Display Records\n3 : Clear All Records\n4 :
Exit\n\nYour Choice : ");
int choice = Integer.parseInt(br.readLine());
switch(choice)
{
case 1:
addRecords();
break;
case 2:
readRecords();
break;
case 3:
clear();
break;
case 4:
System.exit(1);
break;
default:
System.out.println("\nInvalid Choice !");
break;
}
}
public static void main(String args[]) throws
IOException
{
StudentRecords call = new StudentRecords();
call.showMenu();
}
}
Serialization
 Serialization in Java is a mechanism of writing the
state of an object into a byte-stream.

 The reverse operation of serialization is


called deserialization where byte-stream is converted
into an object.
Serialization
Advantages
 It is mainly used to travel object's state on the
network(Distributed systems).
 Send over the network or save it as file or store in DB
for later usage.
Object Serialization and
Deserialization
 object serialization where an object can be represented
as a sequence of bytes that includes the object's data as
well as information about the object's type and the
types of data stored in the object.
 After a serialized object has been written into a file, it
can be read from the file and deserialized that is, the
type information and bytes that represent the object
and its data can be used to recreate the object in
memory.
Object Serialization
 Read/Write entire Object from/to File
 Classes ObjectInputStream and ObjectOutp
utStream are high-level streams that contain
the methods for serializing and deserializing an
object.
Object Serialization
 Classes
 ObjectInputStream implements ObjectInput
 ObjectOutputStream implements ObjectOutput
 Interfaces
 ObjectOutput – writeObject ( )  writes into Output
Stream
 ObjectInput – readObject ( )  returns the object
reference from Input Stream
Serialization Example
Deserialization

 101 Ram

101 Ram
Generics
 Parameterized types
 enable to create classes, interfaces, and methods in
which the type of data upon which they operate is
specified as a parameter
 A class, interface, or method that operates on a
parameterized type is called generic, as in generic class
or generic method
 Generics Work Only with Objects
 For example
 Single class - works with different types of data
Generic Class
 A class that can refer to any type is known as a generic class.
 Syntax :
class class-name<type-param-list> { // ... }
 For example
Class MyGen<T>{
T obj;
void display(T obj){ system.outthis.obj=obj;}
T get(){return obj;}
}
T - Type parameter <>
Generic Class
 For example
Generic Class with two parameters
 For example
Generic Method
Generic Interface
 an interface is defined using generic type parameter
 Syntax
interface interface-name<T>
{
void method-name(T t); // public abstract method.
}
class class-name<T> implements interface-name<T>
{
public void method-name(T t)
{ // code
}
}
Generic Interface
Example
public interface A <T> {
public void display(T t);
}

public class Test<T> implements A <T> {


public void display(T t) {
System.out.println(t);
}
public static void main(String[] args) {
Test<Integer> t = new Test<Integer>();
t.display(100);
Test<String> t2 = new Test<String>();
t2.display(“Ram");
} 25
} Ram
Collection Framework
 is a sophisticated hierarchy of interfaces and classes
 Collection of Objects
 managing groups of objects
 java.util package
Hierarchy of Collection Framework
Iterator<T> iterator()
Iterator
add(), remove(), size()
isEmpty(), Contains()
Clear(), etc,. hasNext(), next(), remove()

Source: javatpoint
Collection Framework
 The Collection in Java is a framework that provides an
architecture to store and manipulate the group of
objects.
 Java Collections can achieve all the operations that you
perform on a data such as searching, sorting, insertion
and deletion.
 Java Collection means a single unit of objects.
 Java Collection framework provides many interfaces
and classes
 Interfaces - Set, List, Queue, Deque
 Classes - ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet.
Source: javatpoint
 What is Collection in Java
 A Collection represents a single unit of objects, i.e., a
group.
 What is a framework in Java
 It provides readymade architecture.
 It represents a set of classes and interfaces.
 It is optional.
 What is Collection framework
 The Collection framework represents a unified
architecture for storing and manipulating a group of
objects. It has:
 Interfaces and its implementations, i.e., classes

Source: javatpoint
Iterable Interface
 The Iterable interface is the root interface for all the
collection classes.
 The Collection interface extends the Iterable interface
and therefore all the subclasses of Collection interface
also implement the Iterable interface.
Iterator<T> iterator()
 It returns the iterator over the elements of type T.
Collection Interface
 Collection interface is implemented by all the classes
in the collection framework.
 It declares the methods that every collection will have.
 The Collection interface builds the foundation on
which the collection framework depends.
 Some of the methods of Collection interface are
 Boolean add ( Object obj),
 void clear(), etc.
 which are implemented by all the subclasses of
Collection interface.
Collection Interface
 Common Methods on Collections
 add()
 remove()
 get()
 size()
 isEmpty()
 Contains()
 Clear()
List Interface
 List interface is the child interface of Collection
interface.
 It inhibits a list type data structure in which we can
store the ordered collection of objects.
 It can have duplicate values.
 List interface is implemented by the classes ArrayList,
LinkedList, Vector, and Stack.
List Interface
 To instantiate the List interface, we must use :
 List <data-type> list1= new ArrayList();
 List <data-type> list2 = new LinkedList();
 List <data-type> list3 = new Vector();
 List <data-type> list4 = new Stack();
 There are various methods in List interface that can be
used to insert, delete, and access the elements from
the list.
Iterator Interface
 provides the facility of iterating the elements in a
forward direction only

N Method Description
o.
1 Public boolean It returns true if the iterator has more elements
hasNext() otherwise it returns false.
2 public Object next() It returns the element and moves the cursor
pointer to the next element.
3 public void remove() It removes the last elements returned by the
iterator. It is less used.
ArrayList
 The ArrayList class implements the List interface.
 It uses a dynamic array to store the duplicate element
of different data types.
 The ArrayList class maintains the insertion order and
is non-synchronized.
 The elements stored in the ArrayList class can be
randomly accessed.
ArrayList Class
 implements the List interface
ArrayList – add() method
ArrayList – add() - specified position
ArrayList – remove()
ArrayList – isempty()
ArrayList - Contains(searching)
Example
LinkedList
 LinkedList implements the Collection interface.
 It uses a doubly linked list internally to store the
elements.
 It allows duplicate elements.
 It maintains the insertion order and not synchronized.
 In LinkedList, the manipulation is fast because no
shifting is required.
LinkedList
LinkedList
 It implements Deque Interface
 addFirst() or offerFirst()
 addLast() or offerLast()
 getFirst( ) or peekFirst( ).
 getLast( ) or peekLast( )
 removeFirst( ) or pollFirst( ).
 removeLast( ) or pollLast( ).
Vector
 Vector uses a dynamic array to store the data elements.
 It is similar to ArrayList.
 However, It is synchronized.
Example
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){ Output:
System.out.println(itr.next());
} Ayush
} Amit
} Ashish
Garima
Vector
 addElement()
 firstElement()
 lastElement()
 insertElementAt(E element,int index)
 capacity() – 10 by default
 removeElement(Object element)
 removeElementAt(int index)
 elementAt(int index)
ArrayList vs LinkedList vs Vector
ArrayList LinkedList Vector
Storage dynamic array to doubly linked dynamic array to store
store the list to store the the elements.
elements. elements
Insertion Order It maintains It maintains

Synchronized No No Yes
Duplicate It allows It allows It allows
elements
Manipulation Slow since Fast, uses a Fast,compared to
speed shifting is doubly linked list ArrayList
required internally
Benefit Better for storing Better for Better for storing and
and accessing manipulation accessing data
data
Random access Yes No yes
Stack
 The stack is the subclass of Vector.
 It implements the last-in-first-out data structure, i.e.,
Stack.
 The stack contains all of the methods of Vector class
and also provides its methods like
 push()
 pop()
 peek() – returns top object but does not remove
 empty()
 search(Object element) – returns
Example
import java.util.*;
public class TestJavaCollection4{
public static void main(String
args[]){ Output:
Stack<String> stack = new
Stack<String>(); Ayush
stack.push("Ayush"); Garvit
stack.push("Garvit");
Amit
stack.push("Amit");
stack.push("Ashish"); Ashish
stack.push("Garima");
stack.pop();
Iterator<String>
itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Queue Interface
 Queue interface maintains the first-in-first-out order.
 It can be defined as an ordered list that is used to hold
the elements which are about to be processed.
 There are various classes like PriorityQueue, Deque
which implements the Queue interface.

 Queue interface can be instantiated as:


 Queue<String> q1 = new PriorityQueue();
Deque Interface
 Deque interface extends the Queue interface. In
Deque, we can remove and add the elements from
both the side.
 Deque stands for a double-ended queue which
enables us to perform the operations at both the
ends.
 Deque can be instantiated as:
Deque d = new ArrayDeque();
ArrayDeque
 ArrayDeque class implements the Deque interface.
 It facilitates us to use the Deque.
 Unlike queue, we can add or delete the elements
from both the ends.
 ArrayDeque is faster than ArrayList and Stack and
has no capacity restrictions.
Example
import java.util.*;
public class TestJavaCollection6{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str); Output:
}
} Gautam
} Karan
Ajay
Set Interface
 It extends the Collection interface.
 It represents the unordered set of elements which
doesn't allow us to store the duplicate items.
 We can store at most one null value in Set.
 Set is implemented by HashSet, LinkedHashSet, and
TreeSet.
Set Interface
 Set can be instantiated as:

Set<data-type> s1 = new HashSet<data-type>();


Set<data-type> s2 = new LinkedHashSet<data-
type>();
Set<data-type> s3 = new TreeSet<data-type>();
HashSet
 HashSet class implements Set Interface.
 It represents the collection that uses a hash table for
storage.
 Hashing is used to store the elements in the HashSet.
 It contains unique items.
Example
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements Output:
HashSet<String> set=new HashSet<String>();
set.add("Ravi"); Vijay
set.add("Vijay"); Ravi
set.add("Ravi");
Ajay
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
TreeSet
 Java TreeSet class implements the Set interface that
uses a tree for storage.
 Like HashSet, TreeSet also contains unique
elements.
 However, the access and retrieval time of TreeSet is
quite fast.
 The elements in TreeSet stored in ascending order.
Example
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements Output:
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi"); Ajay
set.add("Vijay"); Ravi
set.add("Ravi");
Vijay
set.add("Ajay");
//traversing elements ascending order
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
LinkedHashSet
 LinkedHashSet maintains a linked list of the entries in
the set, in the order in which they were inserted.
LinkedHashSet
Map
 A map contains values on the basis of key, i.e. key and
value pair.
 Each key and value pair is known as an entry.
 A Map contains unique keys.
 A Map is useful if you have to search, update or delete
elements on the basis of a key.
 put()
 get()
 remove()
Map
LinkedHashMap
 Java LinkedHashMap contains values based on the key.
 Java LinkedHashMap contains unique elements.
 Java LinkedHashMap may have one null key and
multiple null values.
 Java LinkedHashMap is non synchronized.
 Java LinkedHashMap maintains insertion order.
Linked HashMap
Tree Map
 Java Tree Map contains values based on the key.
 Java Tree Map contains only unique elements.
 Java Tree Map cannot have a null key but can have
multiple null values.
 Java Tree Map is non synchronized.
 Java Tree Map maintains ascending order.
TreeMap
Lambda Expression
 an anonymous (unnamed) method.
 to implement a method defined by a functional
interface
 functional interface
 contains one and only abstract method
 represents a single action
 Example :
 Runnable – run()
Lambda Expression
 Syntax:
(parameter list) -> { body }
 Parameter list - empty or non empty
 Arrow - to link patermeter list and body of expression
 Body – expressions and statements
 No parameter
 () -> { body }
 One parameter
 (P) -> { body }
 Multiple parameters
 (P1, P2) -> { body }
Lambda Expression
interface Student{
public void display();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
String name="Ram";

//without lambda, Drawable implementation using anonymous


class
Student s=new Student(){
public void draw(){System.out.println("Name "+name);}
};
s.display();
}
}
Lambda Expression
interface Student{
public void display();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
String name="Ram";

//without lambda, Drawable implementation using anonymous


class
Student s=()->{
public void draw(){System.out.println("Name "+name);}
};
s.display();
}
}

You might also like