0% found this document useful (0 votes)
34 views19 pages

JPR Notes 6.managing Input Output Files in Java 1

The document discusses Java streams and collection framework. It describes input and output stream classes used for reading and writing bytes as well as character stream classes. It also discusses serialization and deserialization in Java and provides an example. Finally, it provides an introduction to collections in Java including the collection hierarchy and the ArrayList class.

Uploaded by

seemakasture75
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
34 views19 pages

JPR Notes 6.managing Input Output Files in Java 1

The document discusses Java streams and collection framework. It describes input and output stream classes used for reading and writing bytes as well as character stream classes. It also discusses serialization and deserialization in Java and provides an example. Finally, it provides an introduction to collections in Java including the collection hierarchy and the ArrayList class.

Uploaded by

seemakasture75
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 19

Chapter 6

File I/O & collection frame work


Stream Classes
In Java, a stream is a path along which the data flows. Every stream has
a source and a destination.Two fundamental types of streams are Writing
streams and Reading streams. While an Writing streams writes data into
a source(file) , an Reading streams is used to read data from a source(file).

In Java, a stream is a path along which the data flows. Every stream has
a source and a destination. We can build a complex file processing sequence
using a series of simple stream operations. Two fundamental types of streams
are Writing streams and Reading streams. While an Writing streams writes
data into a source(file) , an Reading streams is used to read data from
a source(file).
Stream Classes

Types of Streams
The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized into
two groups based on the data type on which they operate.

 Byte stream classes


 Character stream classes

Byte Stream Classes


Byte stream classes have been designed to provide functional features for creating
and manipulating streams and files for reading and writing bytes. Java provides
two kinds of byte stream classes: input stream classes andoutput stream classes.
Input Stream Classes
Input stream classes that are used to read bytes include a super class known
as Inputstream. The input stream class defines methods for performing input
functions.

Important Methods in the InputStream Class


Methods Usage

read( ) To read a byte from the input stream

read(byte b[ ]) To read an array of b.length bytes into array b

read(byte b[ ], int n, int m) To read m bytes into b starting from n’th byte

available( ) To give the number of bytes available in the input

skip(n) To skip over and discard n bytes from the input stream

reset( ) To go back to the beginning of the stream

close( ) To close the input stream


Output Stream Classes
Output stream classes are derived from the base class Outputstream like
InputStream, the OutputStream is an abstract class and therefore we cannot
instantiate it. The several subclasses of the OutputStream can be used for
performing the output operations.

Important Methods in the OutputStream Class


Methods Usage

write( ) To write a byte to the outputstream

write(byte b[ ]) To write all bytes in the array b to the output stream

write(byte b[ ], int n, int m) To write m bytes from array b starting from n’th byte

close( ) To close the output stream

flush( ) To flush (i.e. clear) the output stream


Character Stream Classes
Character streams can be used to read and write 16-bit Unicode characters. Like
byte streams, there are two kinds of character stream classes, namely, reader
stream classes and writer stream classes.

Reader Stream Classes


Reader stream classes that are used to read characters include a super class known
as Reader and a number of subclasses for supporting various input-related
functions. Reader stream classes are functionally very similar to the input stream
classes, except input streams use bytes as their fundamental unit of information,
while reader streams use characters.

Writer Stream Classes


Like output stream classes, the writer stream classes are designed to perform all
output operations on files. Only difference is that while output stream classes are
designed to write bytes, the writer stream are designed to write character.
The Writer class is an abstract class which acts as a base class for all the other
writer stream classes.
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();
}
}
}
}

First create a file input.txt and write some content int it.
After running the program output.txt will automatically created.

/* Display a text file.


To use this program, specify the name of the file that you want to see.
For example, to see a file called input.txt , use the following command
line.
java ShowFile input.txt
*/
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
return;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Usage: ShowFile File");
return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1)
System.out.print((char) i);
}
while(i != -1);
fin.close();
}}
/* Copy a text file.
To use this program, specify the name of the source file and the destination file.
For example, to copy a file called FIRST.TXT to a file called SECOND.TXT, use
the following command line. java CopyFile FIRST.TXT SECOND.TXT
*/
import java.io.*;
class CopyFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
FileOutputStream fout;
try {
// open input file
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Input File Not Found");
return;
}
// open output file
try {
fout = new FileOutputStream(args[1]);
} catch(FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: CopyFile From To");
return;
}
// Copy File
try {
do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);
} catch(IOException e) {
System.out.println("File Error");
}
fin.close();
fout.close();
}
}

/* program for echo


import java.io.*;
class BufferedReaderCharDemo
{
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, press 'q' to quit.");
// read characters
do
{
c = (char) br.read();
System.out.println(c);
} while(c!='q');
}
}

Java Program To Find Number Of Characters,


Words And Lines In A File :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class WordCountInFile


{
public static void main(String[] args)
{
BufferedReader reader = null;

int charCount = 0;
int wordCount = 0;

int lineCount = 0;

try
{

reader = new BufferedReader(new FileReader("input.txt"));

String currentLine = reader.readLine();

while (currentLine != null)


{

lineCount++;

String[] words = currentLine.split(" ");

wordCount = wordCount + words.length;

for (String word : words)


{

charCount = charCount + word.length();


}

currentLine = reader.readLine();
}

System.out.println("Number Of Chars In A File : "+charCount);

System.out.println("Number Of Words In A File : "+wordCount);

System.out.println("Number Of Lines In A File : "+lineCount);


}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}

Serialization and Deserialization in Java


Serialization in Java is a mechanism of writing the state of an object into a byte stream.

It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

The reverse operation of serialization is called deserialization.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (which is known as marshaling).
Example of Java Serialization
In this example, we are going to serialize the object of Student class. The writeObject() method
of ObjectOutputStream class provides the functionality to serialize the object. We are saving the
state of the object in the file named input.txt.

import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}

Save and compile Student.java

import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,"ravi");

FileOutputStream fout=new FileOutputStream("input.txt");


ObjectOutputStream out=new ObjectOutputStream(fout);

out.writeObject(s1);
out.flush();
System.out.println("success");
}
}

Save and compile Persist.java

6.2 Introduction to collections frame work

Collections in Java
The Collection in Java is a framework that provides an architecture to store and manipulate the
group of objects.

All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion, etc. can be achieved by Java Collections.

What is Collection in java


A Collection represents a single unit of objects, i.e., a group.

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all the classes
and interfaces for Collection framework.
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

Constructors of Java ArrayList


Constructor Description
ArrayList() It is used to build an empty array list.
ArrayList(Collection c) It is used to build an array list that is initialized with the
elements of the collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial
capacity.

Java ArrayList Example


import java.util.ArrayList;
import java.util.Arrays;

class Test

public static void main(String args[])

/* ........... Normal Array............. */

// Need to specify the size for array

int[] arr = new int[3];

arr[0] = 1;

arr[1] = 2;

arr[2] = 3;

/*............ArrayList..............*/

// Need not to specify size

ArrayList<Integer> arrL = new ArrayList<Integer>();

arrL.add(1);

arrL.add(2);

arrL.add(3);

arrL.add(4);

// We can add more elements to arrL

System.out.println(arrL);

System.out.println(Arrays.toString(arr));

}
java.util.Date
The java.util.Date class represents date and time in java. It provides constructors and methods to
deal with date and time in java.

java.util.Date Constructors

No. Constructor Description


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.

public class UtilDateExample1{

public static void main(String args[]){

java.util.Date date=new java.util.Date();

System.out.println(date);

}}

Compile by: javac UtilDateExample1.java

Run by: java UtilDateExample1

Fri Aug 24 12:29:49 IST 2018


Write syntax and function of following methods of data class:

1. Sethme () // The method name has to be setTime()

2. getDay()

1. setTime():

void setTime(long time): the parameter time - the number of milliseconds. Sets this
Date object to represent a point in time that is time milliseconds after January 1,
1970 00:00:00 GMT 2.getDay()

int getDay():Returns the day of the week represented by this date. The returned
value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 =
Friday, 6 = Saturday) represents the day of the week that contains or begins with
the instant in time represented by this Date object, as interpreted in the local time
zone.

What is use of setclass? Write a program using setclass.


( any other suitable example may also be considered.) [2-marks for Set class, 2-marks for Program]
Note: Assuming Set interface in place of set class. Answer is as follows: The Set interface defines a
set. It extends Collection and declares the behavior of a collection that does not allow duplicate
elements. Therefore, the add( ) method returns false if an attempt is made to add duplicate
elements to a set. The Set interface contains only methods inherited from Collection and adds the
restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior
of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if
their implementation types differ. The methods declared by Set are summarized in the following
table:

SN Methods with Description


1 add() Adds an object to the collection
2 clear() Removes all objects from the collection
3 contains() Returns true if a specified object is an element within the
collection
4 isEmpty() Returns true if the collection has no elements
5 iterator() Returns an Iterator object for the collection which may be used to
retrieve an object
6 remove() Removes a specified object from the collection
7 size() Returns the number of elements in the collection
Following is the example to explain Set functionality

import java.util.*;

public class SetDemo

public static void main(String args[])


{

int count[] = {34, 22,10,60,30,22};

Set<Integer> set = new HashSet<Integer>();

try{

for(int i = 0; i<5; i++){

set.add(count[i]);

System.out.println(set);

TreeSet sortedSet = new TreeSet<Integer>(set);

System.out.println("The sorted list is:");

System.out.println(sortedSet);

System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());

System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());

catch(Exception e){}

}}

Executing the program.

[34, 22, 10, 30, 60]

The sorted list is:

[10, 22, 30, 34, 60]

The First element of the set is: 10

The last element of the set is: 60

You might also like