Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java 3 RD

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

UNIT-3

I/O STREAMS AND COLLECTIONS


I/O STREAMS: (Logical connection between java program and a files)
In Java, streams are the sequence of data that are read from the source and written to the destination. An input
stream is used to read data from the source. And, an output stream is used to write data to the destination. In
java we can process the input and produce the output by using I/O streams. A stream is a sequence of objects
that supports various methods which can be pipelined to provide the desired result.
Example:

class CseFinal {
public static void main(String [] args) {
system.out.println(“Cse,Final”);
}}

 A stream is an abstraction that either produces or consumes information.


 Java provides two types of streams input and output streams.
 In java, a stream is a path along which the data flow.
 Every stream has a source and destination.
 We can build a complex files processing sequence using a series of simple stream operations.
 Two fundamental types of streams are writing streams and reading streams.
 A writing stream is writing data into a source, a reading stream is used to read data from a source.
 An input stream can abstract many different types of input from keyboard, a file on disk, a network or
from another program.
 Similarly an output stream may refer to the console, a disk file, or network connection
Need of an I/O streams:
We can store data permanently in files by performing persistence operations. But streams are facing several
problems with file operations those are searching, sorting and insertion. To overcome this problems in java
streams, the sun-micro systems introduced the JDBC (java data base connectivity) API and network API to
the files.
Streams are classified into two types.
 Byte streams.
 Character stream.
Byte streams:
Byte stream is used to read and write a single byte (8 bits) of data. All byte stream classes are derived from
base abstract classes called Input Stream and Output Stream.
 Input Stream Class
 Output Stream Class

S Class Description
N

1 BufferedInputStream This class provides methods to read bytes from the buffer.

2 ByteArrayInputStream This class provides methods to read bytes from the byte array.

3 DataInputStream This class provides methods to read Java primitive data types.
4 FileInputStream This class provides methods to read bytes from a file.

5 FilterInputStream This class contains methods to read bytes from the other input streams,
which are used as the primary source of data.

6 ObjectInputStream This class provides methods to read objects.

7 PipedInputStream This class provides methods to read from a piped output stream to
which the piped input stream must be connected.

8 SequenceInputStream This class provides methods to connect multiple Input Stream


and read data from them.

Character stream:
Character stream is used to read and write a single character of data. All the character stream classes are
derived from base abstract classes Reader and Writer.
 Reader Class
 Writer Class

S Class Description
N

1. BufferedReader This class provides methods to read characters from the buffer.

2. CharArrayReader This class provides methods to read characters from the char array.

3. FileReader This class provides methods to read characters from the file.

4. FilterReader This class provides methods to read characters from the underlying character input
stream.

5 InputStreamReader This class provides methods to convert bytes to characters.

6 PipedReader This class provides methods to read characters from the connected piped output
stream.

7 StringReader This class provides methods to read characters from a string

DATA THROUGH CONSOLE INPUT & OUTPUT STREAMS WITH EXAMPLES


There are different ways to read data from and write to the system console. A console is generally connected
with javstring a processes which are started using command-line tool. It is important to note that if the java
process has started automatically, the console may not be available for input and output purposes
system.console() will return null.
Reading input from console
Console gives three ways to read the input:
 String readLine() reads a single line of text from the console.
 Char[] readPassword() read a password or encrypted text from the console with echoing disabled.
 Reader reader() retrieves the reader object associated with this console.
readLine():
Console console=System.console();
if(console==null){
system.out.println(“console is not available to current JVM process”);
return; }
string username=console.readLine(“enter the username:”);
system.out.println(“entered username:”+ username);
readPassword():
Console console=System.console();
if(console==null){
system.out.println(“console is not available to current JVM process”);
return; }
char[] password=console.readPassword(“enter the username:”);
system.out.println(“entered password:”+ new String(password));
reader():
Console console=System.console();
If(console==null){
System.out.println(“console is not available to current JVM process”);
return; }
Reader consoleReader=console.reader();
Scanner scanner= new scanner(consoleReader);
System.out.println(“enter age:”);
int age=scanner.nextInt();
system.out.println(“entered age:”+age);
scanner.close();
Output to console:
 To write the output data to console is system.out.println() statements.
 And we can also use printf() methods to write formatted text to console.

Writing with system.out.println():
System.out.println(“hello java”);
Writing with printf():
String name= “java”;
Int age= 26;
Console.printf(“my name is %s and my age is %d”, name, age);

DATA INPUT STREAM AND DATA OUTPUT STREAM TO ACCESS PRIMITIVE DATA TYPES
DATA INPUT STREAM
Data input stream is used to read primitive data types from an input source.
*Constructor of data input stream is data input (input stream in).
*Methods of data input stream (Public string read Line() throws IO Exception
Sample program:
import java.io.DataInputStream;
import java.io.FileInputStream;
class IOTest
{
public void raedFile()
{
try
{
FileInputSttream object
FileInputStream fis=new FileInputStream(“F:\\new folder\\data1.txt”);
DataInputStream dis=new DataInputStream(fis);
int I;
while((i=dis.read())!=-1)
{
system.out.print((char)!);
}}
catch (Exception e)
{
e.printStack Trace();
}}}
Public class DataInputStreamExample
{
Public static vaoid main(String args[])
{
IOTest obj=new IO Test();
Obj.readFile();
}}

DATA OUTPUT STREAM


Data output stream is used to write primitive data types to an output source.
*Constructors of data output stream is (output stream out).
*Methods of data output stream (public final void write bytes(strings) throws IO Exception).
Sample program:
import java.io.DataOutputStream;
import java.io.FileOutputStream;
class IOTest
{
String str= “Hello www.w3spoint.com”;
public void writeFile()
{
try
{
FileOutputStream fos=new FileOutputStream(“F:\\new folder\\data4.txt”);
DataOutputStream dos=new DataOutputStream(fos);
byte b[]=str.getBytes();
dos.write(b);
dos.flush();
dos.close();
System.out.println(“contents written successfully.”);
}
catch (Exception e)
{
e.printStack Trace();
}}}
public class DataOutputStreamExample
{
public static void main(String args[])
{
IOTest obj=new IOTest();
Obj.writeFile();
}}

VARIOUS FILE ACCESS OPERATIONS BY USING FILE STREAMS


In java a file is an abstract data type. A named location used to store related information is known as a file.
There are several file operations like
 Creating a new file,
 Getting file information about file,
 Writing into a file,
 Reading in to a file
 Deleting a file.
Various file class methods
Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

Create new file:


The createNewFile() function is a part of File class in Java . This function creates new empty file. The
function returns true if the abstract file path does not exist and a new file is created. It returns false if the
filename already exists.
Syntax: boolean var = file.createNewFile();
Example:
import java.io.*;
public class solution {
public static void main(String args[])
{
try {
File f = new File("F:\\program.txt");
if (f.createNewFile())
System.out.println("File created");
else
System.out.println("File already exists");
}
catch (Exception e) {
System.err.println(e);
}
}
}

Get file information:


The operation is performed to get the file information. We use several methods to get the information about
the file like name, absolute path, is readable, is writable and length.
Program:
import java.io.File;
class FileInfo {
public static void main(String[] args) {
File f0 = new File("D:FileOperationExample.txt");
if (f0.exists()) {
System.out.println("The name of the file is: " + f0.getName());
System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());
System.out.println("Is file writeable?: " + f0.canWrite());
System.out.println("Is file readable " + f0.canRead());
System.out.println("The size of the file in bytes is: " + f0.length());
} else {
System.out.println("The file does not exist.");
}
}
}

Write into a file:


Writing into a file is in order to write data into a file, we will use the FileWriter class and its write() method
together. We need to close the stream using the close() method to retrieve the allocated resources.
Example:
import java.io.FileWriter;
import java.io.IOException;
class WriteToFile {
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
fwrite.write("A named location used to store related information is referred to as a File.");
fwrite.close();
System.out.println("Content is successfully wrote to the file.");
} catch (IOException e) {
System.out.println("Unexpected error occurred");
e.printStackTrace();
}
}
}

Read from a file:


Read from a file is in order to write data into a file, we will use the Scanner class. Here, we need to close the
stream using the close() method. We will create an instance of the Scanner class and use the hasNextLine()
method nextLine() method to get data from the file.
Example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
class ReadFromFile {
public static void main(String[] args) {
try {
File f1 = new File("D:FileOperationExample.txt");
Scanner dataReader = new Scanner(f1);
while (dataReader.hasNextLine()) {
String fileData = dataReader.nextLine();
System.out.println(fileData);
}
dataReader.close();
} catch (FileNotFoundException exception) {
System.out.println("Unexcpected error occurred!");
exception.printStackTrace();
}
}
}
Delete a file:
Deleting a file is in order to delete a file, we will use the delete() method of the file. We don't need to close
the stream using the close() method because for deleting a file, we neither use the FileWriter class nor the
Scanner class.
Example:
import java.io.File;
class DeleteFile {
public static void main(String[] args) {
File f0 = new File("D:FileOperationExample.txt");
if (f0.delete()) {
System.out.println(f0.getName()+ " file is deleted successfully.");
} else {
System.out.println("Unexpected error found in deletion of the file.");
}
}
}

COLLECTIONS
A collection is framework provided by JAVA. a collection sometimes called as container is simply an object
that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate and
communicate aggregate data. This framework provides many interfaces and their implemented classes in
order to store group of objects in single entity.
 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
 Algorithm
Hierarchy of collection framework

Array List
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit. We can add or remove elements anytime. The ArrayList in Java can have the duplicate elements
also.
Program:
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("Mango"); //Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
System.out.println(list);
}
}

Linked List:
Java Linked List class uses a doubly linked list to store the elements. It provides a linked-list data
structure.
Program:
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

ITERATOR AND LIST ITERATOR INTERFACE METHODS


Iterator:
The iterator interface of the java collections framework allows us to access elements of a collection. It
has one sub interface is list iterator. This will traverse data only the forward direction.
Methods:
 hasNext()
 next()
 remove()
 forEachRemaining()
Example program:
import java.io.*;
import java.util.*;
public class JavaIteratorExample {
public static void main(String[] args)
{
ArrayList<String> cityNames = new ArrayList<String>();
cityNames.add("Delhi");
cityNames.add("Mumbai");
cityNames.add("Kolkata");
cityNames.add("Chandigarh");
cityNames.add("Noida");
Iterator iterator = cityNames.iterator();
System.out.println("CityNames elements : ");
while (iterator.hasNext())
System.out.print(iterator.next() + " ");
System.out.println();
} }
List iterator:
The list iterator interface of the java collections framework provides the functionality to access elements of a
list. It is bi-directional. Both forward and backward direction traversal of data.
Methods:
 hasNext()
 next()
 nextIndex()
 previous()
 previousIndex()
 remove()
 set()
Example program:
import java.util.ArrayList;
import java.util.ListIterator;
class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(2);
System.out.println("ArrayList: " + numbers);
ListIterator<Integer> iterate = numbers.listIterator();
int number1 = iterate.next();
System.out.println("Next Element: " + number1);
int index1 = iterate.nextIndex();
System.out.println("Position of Next Element: " + index1);
System.out.println("Is there any next element? " + iterate.hasNext());
}
}

HashSet
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table
for storage. A hash table stores information by using a mechanism called “hashing”. In hashing the
information content of a key is used to determine a unique value, called its “hash code”. The transformation
of the key into its hash code is performed automatically.
Program:
import java.util.*;
class HashSet1
{
public static void main(String args[])
{
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Hash table:
Hash table was a part of the original java.util and is a concrete implementation of a dictionary. It is an
integration of collection framework.
Program:
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

MAP INTERFACE
Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.
Given a key and a value you can store the value in a map object. After the value is stored you can retrieve it
by using its key.
Program:
import java.util.*;
class MapExample2{
public static void main(String args[]){
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(100,"Amit");
map.put(101,"Vijay");
map.put(102,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Hash map:
The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic
operations, such as get() and put(), to remain constant even for large sets.
Programm:
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
} }
ENUMSET:
EnumSet is a specialized implementation of the Set interface for enumeration types. It implements the Set
interface and extends the AbstractSet. Enumset class is a member of the java collections framework and it is
not synchronized. Enumset is much faster than HashSet.
Program:
import java.util.*;
enum days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample {
public static void main(String[] args) {
Set<days> set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);
// Traversing elements
Iterator<days> iter = set.iterator();
while (iter.hasNext())
System.out.println(iter.next());
}
}

ENUM MAP:
An EnumMap is a specialized implementation of the Map interface for enumeration types. It implements the
Map interface and extends AbstractMap in java. EnumMap is much faster than HashMap.
Program:
import java.util.*;
public class EnumMapExample {
// create an enum
public enum Days {
Monday, Tuesday, Wednesday, Thursday
};
public static void main(String[] args) {
EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class);
map.put(Days.Monday, "1");
map.put(Days.Tuesday, "2");
map.put(Days.Wednesday, "3");
map.put(Days.Thursday, "4");
// print the map
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

DIFFERENCES BETWEEN ENUMSET AND ENUMMAP


EnumMap EnumSet

EnumMap is a specialized implementation of the EnumSet is a specialized implementation of the Set


Map interface for the enumeration types. interface for the enumeration types.

EnumMap is internally represented as an array. EnumSet is internally represented as a BitVector.

EnumMap doesn’t allow to insert the null keys,


EnumSet doesn’t allow inserting null elements.
however, null values can be inserted.
EnumMap EnumSet

EnumMap is not an abstract class. EnumSet is an abstract class.

EnumMap is not an abstract class therefore, we EnumSet is an abstract class therefore, we can not
can create an instance of this class. create the instance of this class.

You might also like