0% found this document useful (0 votes)
18 views40 pages

Unit II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views40 pages

Unit II

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

II UNIT

Packages in Java

➢ Packages in Java are a way of grouping similar types of classes /


interfaces together. It is a great way to achieve reusability.
➢ We can simply import a class providing the required functionality from
an existing package and use it in our program. A package basically acts
as a container for group of related classes.
➢ The concept of package can be considered as means to achieve data
encapsulation.

Packages are categorized as:


1 ) Built-in packages ( standard packages which come as a part of Java
Runtime Environment )
2 ) User-defined packages ( packages defined by programmers to bundle
group of related classes )

Built-in Packages:
These packages consists of a large number of classes which are a part of Java
API.
For e.g: we have used java.io package previously which contain classes to
support input / output operations in Java. Similarly, there are other packages
which provides different functionality.

Some of the commonly used built-in packages are shown in the table below :

Package
Description
Name
Contains language support classes ( for e.g classes which defines
java.lang primitive data types, math operations, etc.) . This package is
automatically imported.
java.io Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like
java.util Linked List, Hash Table, Dictionary, etc and support for Date /
Time operations.
java.applet Contains classes for creating Applets.
Contains classes for implementing the components of graphical
java.awt
user interface ( like buttons, menus, etc. ).
java.net Contains classes for supporting networking operations.

Accessing classes in a Built-in package in to a program :

1
1 ) import java.util.Vector; // import the Vector class from util package
or
2 ) import java.util.*; // import all the class from util package

➢ First statement imports Vector class from util package which is


contained inside java package.
➢ Second statement imports all the classes from util package.

User-defined packages:

➢ Creating a Package:

While creating a package, you should choose a name for the package and
include a package statement along with that name at the top of every
source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.

forExample: package Mypack;

The package statement should be the first line in the source file. There can be
only one package statement in each source file, and it applies to all types in the
file.

To compile the Java programs with package statements, you have to use -d
option as shown below.

javac -d Destination_folder file_name.java

How to run java package program:

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

Compile: javac -d . file_name.java

Run: java mypack.file_name

➢ Importing Packages

The general form of the import statement:


2
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that
imposed by the file system.

either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.

ForExample:

This code fragment shows both forms in use:

import java.util.Scanner;
import java.io.*;

• The basic language functions are stored in a package inside of the java
package called java.lang. (Default Package)
• This is equivalent to the following line being at the top of all of your
programs:
• import java.lang.*;

There are three ways to access the package from outside the package.

• import package.*;
• import package.classname;
• fully qualified name.

➢ Using packagename ➢ Using


packagename.classname
//save by A.java
If you import package.classname
package pack; then only declared class of this
public class A{ package will be accessible.
public void msg() //save by A.java
{System.out.println("Hello");} package pack;
}
public class A
//save by B.java {
public void msg()
package mypack; { System.out.println("Hello"); } }
import pack.*;
//save by B.java
class B{
package mypack;

3
public static void main(String import pack.A;
args[]){
A obj = new A(); class B{
obj.msg(); public static void main(String
} } args[]) {
A obj = new A();
obj.msg();
Complile: javac –d . B.java }
//(Because MainMethod occurs at }
B.java)

Run: java pack.B Output:Hello


//(Because MainMethod occurs at
B.java)

Output:Hello

Interfaces
Defining an Interface

➢ An interface is a reference type in Java. It is similar to class. It is a


collection of abstract methods.
➢ A class implements an interface, thereby inheriting the abstract
methods of the interface.
➢ The interface in Java is a mechanism to achieve abstraction.
➢ There can be only abstract methods in the Java interface, not method
body.
➢ Along with abstract methods, an interface may also contain constants,
default methods, static methods, and nested types.
➢ Method bodies exist only for default methods and static methods.

Syntax:
access interface name {
return-type method-name (parameter-list); //Abstract Method
type final-varname1 = value;
type final-varname2 = value; //variables
default method-name (parameter-list)
{ //default method body; }

static method-name (parameter-list)


{ //method body }

4
In other words, Interface fields are public, static and final by default, and the
methods are public and abstract.

Implementing Interfaces

➢ Once an interface has been defined, one or more classes can inherit that
interface by using implements Keyword

➢ To implement an interface, include the implements Keyword in a class


definition, and then create the methods defined by the interface.

➢ The methods that implement an interface in a class must be declared with


public accessSpecifier.

Syntax:

class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

If a class implements more than one interface, the interfaces are separated
with a comma.

As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

Nested Interfaces

➢ An interface can be declared a member of a class or another interface. Such


an interface is called a member interface or a nested interface.

5
➢ A nested interface can be declared as public, private, or protected. This
differs from a top-level interface, which must either be declared as public or
use the default access level, as previously described.
➢ When a nested interface is used outside of its enclosing scope, it must be
qualified by the name of the class or interface of which it is a member.
Thus, outside of the class or interface in which a nested interface is
declared, its name must be fully qualified

Here is an example that demonstrates a nested interface:

// A nested interface example.


// This class contains a member interface.

class A {
// this is a nested interface
public interface NestedIF {
boolean isNotNegative(int x);
}
}
// B implements the nested interface.
class B implements A.NestedIF { //nested interface Declaration
public boolean isNotNegative(int x)
{ return x < 0 ? false : true; }
}
class NestedIFDemo {
public static void main(String args[]) {
A.NestedIF nif = new B(); // use a nested interface reference
if(nif.isNotNegative(10))
{ System.out.println("10 is not negative"); }
if(nif.isNotNegative(-12))
{ System.out.println("this won't be displayed"); }
}
}

Note:
Notice that A defines a member interface called NestedIF and that it is
declared public. Next, B implements the nested interface by specifying
implements A.NestedIF

Notice that the name is fully qualified by the enclosing class’ name. Inside the
main( ) method, an A.NestedIF reference called nif is created, and it is
assigned a reference to a B object. Because B implements A.NestedIF, this is
legal.

Applying Interfaces

6
➢ used to achieve abstraction.

//Interface declaration: by first user


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. g
etDrawable()
d.draw();
}}

Output:
drawing circle

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance.

interface Printable{
void print();
}

interface Showable{
void show();
}

7
class A implements Printable,Showable{

public void print(){System.out.println("Hello");}


public void show(){System.out.println("Welcome");}
}

class A7
{
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}

Output:Hello Welcome

Interface inheritance

A class implements an interface, but one interface extends another interface.

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}

Output:
Hello
Welcome

Default Method in Interface

interface Drawable{

8
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}

Output:
drawing rectangle
default method

Static Method in Interface

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}

Output:
drawing rectangle
27
Difference between abstract class and interface

Abstract class Interface


Interface can have only abstract
1) Abstract class can have abstract
methods. Since Java 8, it can have
and non-abstract methods.
default and static methods also.
2) Abstract class doesn't support Interface supports multiple
multiple inheritance. inheritance.

9
3) Abstract class can have final,
Interface has only static and final
non-final, static and non-static
variables.
variables.
4) Abstract class can provide the Interface can't provide the
implementation of interface. implementation of abstract class.
5) The abstract keyword is used to The interface keyword is used to
declare abstract class. declare interface.
6) An abstract classcan extend
An interface can extend another Java
another Java class and implement
interface only.
multiple Java interfaces.
7) An abstract classcan be extended An interface classcan be implemented
using keyword ?extends?. using keyword ?implements?.
8) A Javaabstract classcan have
Members of a Java interface are public
class members like private,
by default.
protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Stream based I/O (java.io)

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.

We can perform file handling in Java by Java I/O API.

Streams

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O
system to make input and output operation in java. In general, a stream means
continuous flow of data. Streams are clean way to deal with input/output without
having every part of your code understand the physical.

In Java, 3 streams are created for us automatically. All these streams are
attached with the console.
1) System.out: standard output stream

10
2) System.in: standard input stream
3) System.err: standard error stream

While File Handling These Streams are processed as two types


They are

➢ inputStream - The InputStream is used to read data from a source.


➢ outputStream - The OutputStream is used for writing data to a destination.

Java defines two types of streams:

1. ByteStreams
2. CharecterStreams

Byte Streams:
➢ A Byte stream will read a file Byte by Byte.
➢ Byte stream is defined by using two abstract class at the top of hierarchy,
they are InputStream and OutputStream.
➢ Java byte streams are used to perform input and output of 8-bit bytes.
Though there are many classes related to byte streams but the most
frequently used classes are, FileInputStream and FileOutputStream.
➢ These two abstract classes have several concrete classes that handle
various devices such as disk files, network connection etc.

Some important Byte stream classes.

Stream class Description

BufferedInputStream Used for Buffered Input Stream.

BufferedOutputStream Used for Buffered Output Stream.

ByteArrayInputStream Input stream that reads from a byte array

11
Output stream that writes to a byte array
ByteArrayOutputStream

Contains method for reading java standard


DataInputStream
datatype

An output stream that contain method for


DataOutputStream
writing java standard data type

FileInputStream Input stream that reads from a file

FileOutputStream Output stream that write to a file.

InputStream Abstract class that describe stream input.

ObjectInputStream Input stream for objects

ObjectOutputStream Output stream for objects

OutputStream Abstract class that describe stream output.

PipedInputStream
Input pipe

PipedOutputStream Output pipe

Output Stream that contain print() and println()


PrintStream
method

RandomAccessFile Supports random access file I/O

Input stream that is a combination of two or


SequenceInputStream
more input streams that
will be read sequentially, one after the other

These classes define several key methods. Two most important are

1. read() : reads byte of data.


2. write() : Writes byte of data.
3. close(): to close allConnections.

12
FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data.

Syntax:

FileInputStream(String filepath)
FileInputStream(File fileObj)

Either can throw a FileNotFoundException.


Here, filepath is the full path name of a file, and fileObj is a File object that describes
the file.

forExample:
FileInputStream f0 = new FileInputStream("abc.txt")
or
File f = new File("abc.txt");
FileInputStream f1 = new FileInputStream(f);

read single character


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}

Output: W
read all characters:

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}

13
}
Output: Welcome to java

FileOutputStream Class:

Java FileOutputStream is an output stream used for writing data to a file.


If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream
class.

Syntax:

FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)

They can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, the file is
opened in append mode.

Creation of a FileOutputStream is not dependent on the file already existing.


FileOutputStream will create the file before opening it for output when you create the
object. In the case where you attempt to open a read-only file, an IOException will be
thrown.

write byte:

public class writebyte {


public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

write string into a file with present data

import java.io.FileOutputStream;
public class writestring {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to JAVA.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);

14
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

write string into a file including with previous data

import java.io.FileOutputStream;
public class writestring {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt",true);
String s="\nWelcome to JAVA.";
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);}
}
}

Copying From one File to another by using FileInputSream and


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

15
}
}
BufferedInputStream class BufferedOutputStream class
Java BufferedInputStream class is used Java BufferedOutputStream class is
to read information from stream. It used for buffering an output stream. It
internally uses buffer mechanism to internally uses buffer to store data. It
make the performance fast. adds more efficiency than to write data
directly into a stream. So, it makes the
performance fast.
Syntax: Syntax:

BufferedInputStream(InputStream BufferedOutputStream(OutputStream
inputStream) outputStream)
or or
BufferedInputStream(InputStream BufferedOutputStream(OutputStream
inputStream, int bufSize) outputStream, int bufSize)

import java.io.*; import java.io.*;


public class public class
BufferedInputStreamExample{ BufferedOutputStreamExample{
public static void main(String args[]){ public static void main(String
try{ args[])throws Exception{
FileInputStream fin=new FileOutputStream fout=new
FileInputStream("D:\\testout.txt"); FileOutputStream("D:\\testout.txt");

BufferedInputStream bin=new BufferedOutputStream bout=new


BufferedInputStream(fin); BufferedOutputStream(fout);
int i; String s="Welcome to JAVA.";
while((i=bin.read())!=-1){ byte b[]=s.getBytes();
System.out.print((char)i); bout.write(b);
} bout.close();
bin.close(); fout.close();
fin.close(); System.out.println("success");
}catch(Exception }
e){System.out.println(e);} }
}
} Output:
Success
Here, we are assuming that you have
following data in "testout.txt" file: testout.txt
Java programing
Output: Welcome to java.
Java programing

16
ByteArrayInputStream class ByteArrayOutputStream class
The ByteArrayInputStream is composed Java ByteArrayOutputStream class is
of two words: ByteArray and used to write common data into
InputStream. As the name suggests, it multiple files. In this stream, the data is
can be used to read byte array as input written into a byte array which can be
stream. written to multiple streams later.
The ByteArrayOutputStream holds a
Java ByteArrayInputStream class copy of data and forwards it to multiple
contains an internal buffer which is used streams.
to read byte array as stream. In this The buffer of ByteArrayOutputStream
stream, the data is read from a byte automatically grows according to data.
array.
The buffer of ByteArrayInputStream
automatically grows according to data.

Syntax: Syntax:
ByteArrayOutputStream( )
ByteArrayInputStream(byte array[ ]) or
or ByteArrayOutputStream(int numBytes)
ByteArrayInputStream(byte array[ ], int
start, int numBytes)

import java.io.*; import java.io.*;


public class ReadExample { public class DataStreamExample {
public static void main(String[] args) public static void main(String
throws IOException { args[])throws Exception{
byte[] buf = { 35, 36, 37, 38 }; FileOutputStream fout1=new
// Create the new byte array input FileOutputStream("D:\\f1.txt");
stream FileOutputStream fout2=new
ByteArrayInputStream byt = new FileOutputStream("D:\\f2.txt");
ByteArrayInputStream(buf);
int k = 0; ByteArrayOutputStream bout=new
while ((k = byt.read()) != -1) { ByteArrayOutputStream();
//Conversion of a byte into bout.write(65);
character bout.writeTo(fout1);
char ch = (char) k; bout.writeTo(fout2);
System.out.println("ASCII value of
Character is:" + k + "; Special character bout.flush();
is: " + ch); bout.close();//has no effect
} System.out.println("Success...");
} }
} }

Output: Output:

ASCII value of Character is:35; Special Success...


character is: #
ASCII value of Character is:36; Special f1.txt:
character is: $
ASCII value of Character is:37; Special A
character is: %

17
ASCII value of Character is:38; Special
character is: &

FilterInputStream class FilterOutputStream class


Java FilterInputStream class implements Java FilterOutputStream class
the InputStream. It contains different implements the OutputStream class. It
sub classes as BufferedInputStream, provides different sub classes such as
DataInputStream for providing BufferedOutputStream and
additional functionality. So it is less used DataOutputStream to provide additional
individually. functionality. So it is less used
individually.

import java.io.*; import java.io.*;


public class FilterExample { public class FilterExample {
public static void main(String[] public static void main(String[]
args) throws IOException { args) throws IOException {
File data = new File data = new
File("D:\\testout.txt"); File("D:\\testout.txt");
FileInputStream file = new FileOutputStream file = new
FileInputStream(data); FileOutputStream(data);
FilterInputStream filter = new FilterOutputStream filter = new
BufferedInputStream(file); FilterOutputStream(file);
int k =0; String s="Welcome to JAVA.";
while((k=filter.read())!=-1){ byte b[]=s.getBytes();
System.out.print((char)k); filter.write(b);
} filter.flush();
file.close(); filter.close();
filter.close(); file.close();
} System.out.println("Success...");
} }
Here, we are assuming that you have }
following data in "testout.txt" file:
Welcome to JAVA Output:
Output: Success...
Welcome to JAVA
testout.txt
Welcome to JAVA.

SequenceInputStream Class:
Java SequenceInputStream class is used to read data from multiple streams. It reads
data sequentially (one by one).

Syntax:
SequenceInputStream(InputStream first, InputStream second)

or
SequenceInputStream(Enumeration <? extends InputStream> streamEnum)
(This constructor u can find by Enumeration process)

18
import java.io.*;
class InputStreamExample {
public static void main(String args[])throws Exception{
FileInputStream input1=new FileInputStream("D:\\testin.txt");
FileInputStream input2=new FileInputStream("D:\\testout.txt");
SequenceInputStream inst=new SequenceInputStream(input1, input2);
int j;
while((j=inst.read())!=-1){
System.out.print((char)j);
}
inst.close();
input1.close();
input2.close();
}
}
Here, we are assuming that you have two files: testin.txt and testout.txt which have
following information:
testin.txt:
Welcome to Java IO Programming.
testout.txt:
It is the example of Java SequenceInputStream class.
After executing the program, you will get following output:
Output: Welcome to Java IO Programming. It is the example of Java
SequenceInputStream class.
Character Stream Classes
A character stream will read a file character by character. Character Stream is a
higher level concept than Byte Stream .

Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for 16-
bit unicode. Though there are many classes related to character streams but
the most frequently used classes are, FileReader and FileWriter.

Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.

Reader

19
Reader is an abstract class that defines Java’s model of streaming character input. It
implements the Closeable and Readable interfaces. All of the methods in this class
(except for markSupported( )) will throw an IOException on error conditions.

Writer
Writer is an abstract class that defines streaming character output. It implements the
Closeable, Flushable, and Appendable interfaces. All of the methods in this class
throw an IOExceptionin the case of errors.

These two abstract classes have several concrete classes that handle unicode
character.

Some important Charcter stream classes.

Stream class Description

BufferedReader Handles buffered input stream.

BufferedWriter Handles buffered output stream.

Input stream that reads from a character array


CharArrayReader

CharArrayWriter Output stream that writes to a character array

FileReader Input stream that reads from file.

FileWriter Output stream that writes to file.

FilterReader
Filtered reader

FilterWriter Filtered writer

InputStreamReader Input stream that translate byte to character

LineNumberReader Input stream that counts lines

OutputStreamReader Output stream that translate character to byte.

PipedReader
Input pipe

PipedWriter Output pipe

20
Output Stream that contain print() and println()
PrintWriter
method.

Input stream that allows characters to be returned


PushbackReader
to the input stream

Reader Abstract class that define character stream input

Input stream that reads from a string


StringReader

StringWriter Output stream that writes to a string

Writer Abstract class that define character stream output

FileReader Class
Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class. It is character-oriented class which is used for file handling
in java.

Syntax:

FileReader(String filePath)
FileReader(File fileObj)

Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file.

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to JAVA.

Output:

Welcome to JAVA.

21
FileWriter Class

Java FileWriter class is used to write character-oriented data to a file. It is character-


oriented class which is used for file handling in java.
Unlike FileOutputStream class, you don't need to convert string into byte array
because it provides method to write string directly.

Syntax:

Its most commonly used constructors are shown here:


FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)

import java.io.FileWriter;
public class FileWriterExample {
public static void main(String args[]){
try{
FileWriter fw=new FileWriter("D:\\testout.txt");
fw.write("Welcome to JAVA.");
fw.close();
}catch(Exception e){System.out.println(e);}
System.out.println("Success...");
}
}
Output: Success...
testout.txt: Welcome to JAVA.

Copying From one File to another by using FileReader and FileWriter classes:

import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {

22
in.close();
}
if (out != null) {
out.close();
}
}
}
}

Now let's have a file input.txt with the following content −

This is test for copy file.

BufferedReader Class BufferedWriter Class


Java BufferedReader class is used to Java BufferedWriter class is used to
read the text from a character-based provide buffering for Writer instances. It
input stream. It can be used to read data makes the performance fast. It inherits
line by line by readLine() method. It Writer class. The buffering characters
makes the performance fast. It inherits are used for providing the efficient
Reader class. writing of single arrays, characters, and
strings.
It has two constructors:
ABufferedWriter has these two
BufferedReader(Reader inputStream) constructors:
BufferedReader(Reader inputStream, int
bufSize) BufferedWriter(Writer outputStream)
BufferedWriter(Writer outputStream, int
The first form creates a buffered bufSize)
character stream using a default buffer
size. In the second, the size of the buffer The first form creates a buffered stream
is passed in bufSize. using a buffer with a default size. In the
second, the size of the buffer is passed in
bufSize.

import java.io.*; import java.io.*;


public class BufferedReaderExample { public class BufferedWriterExample {
public static void main(String public static void main(String[] args)
args[])throws Exception{ throws Exception {
FileReader fr=new FileWriter writer = new
FileReader("D:\\testout.txt"); FileWriter("D:\\testout.txt");
BufferedReader br=new BufferedWriter buffer = new
BufferedReader(fr); BufferedWriter(writer);
buffer.write("Welcome to JAVA.");
int i; buffer.close();
while((i=br.read())!=-1){ System.out.println("Success");
System.out.print((char)i); }
} }
br.close();
fr.close();

23
}
}
Output: Output:
Welcome to JAVA. success

CharArrayReader class CharArrayWriter Class


The CharArrayReader is composed of two The CharArrayWriter class can be used
words: CharArray and Reader. The to write common data to multiple files.
CharArrayReader class is used to read This class inherits Writer class. Its buffer
character array as a reader (stream). It automatically grows when data is written
inherits Reader class. in this stream. Calling the close() method
on this object has no effect.
This class has two constructors, each of
which requires a character array to CharArrayWriter has two constructors,
provide the data source: shown here:

CharArrayReader(char array[ ]) CharArrayWriter( )


CharArrayReader(char array[ ], int start, CharArrayWriter(int numChars)
int numChars)
In the first form, a buffer with a default
size is created. In the second, a buffer is
created with a size equal to that specified
by numChars. The buffer is held in the
buf field of CharArrayWriter.The buffer
size will be increased automatically, if
needed. The number of characters held
by the buffer is contained in the count
field of CharArrayWriter. Both buf and
count are protected fields.

import java.io.CharArrayReader; import java.io.CharArrayWriter;


public class CharArrayExample{ import java.io.FileWriter;
public static void main(String[] ag) public class CharArrayWriterExample
throws Exception { {
char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', public static void main(String
'i', 'n', 't' }; args[])throws Exception{
CharArrayReader reader = new CharArrayWriter out=new
CharArrayReader(ary); CharArrayWriter();
int k = 0; out.write("Welcome to JAVA");
// Read until the end of a file FileWriter f1=new
while ((k = reader.read()) != -1) { FileWriter("D:\\a.txt");
char ch = (char) k; FileWriter f2=new
System.out.print(ch + " : "); FileWriter("D:\\b.txt");
System.out.println(k); FileWriter f3=new
} FileWriter("D:\\c.txt");
} FileWriter f4=new
} FileWriter("D:\\d.txt");

24
out.writeTo(f1);
Output out.writeTo(f2);
out.writeTo(f3);
j : 106 out.writeTo(f4);
a : 97 f1.close();
v : 118 f2.close();
a : 97 f3.close();
t : 116 f4.close();
p : 112 System.out.println("Success...");
o : 111 }
i : 105 }
n : 110
t : 116 Output

Success...

After executing the program, you can see


that all files have common data:
Welcome to JAVA.

a.txt:

Welcome to JAVA

b.txt:

Welcome to JAVA

c.txt:

Welcome to JAVA

d.txt:

Welcome to JAVA

PrintStream Class PrintWriter class


The PrintStream class provides methods Java PrintWriter class is the
to write data to another stream. The implementation of Writer class. It is used
PrintStream class automatically flushes to print the formatted representation of
the data so there is no need to call objects to the text-output stream.
flush() method. Moreover, its methods
don't throw IOException. The following have been supplied by
PrintWriter from the start:
PrintStream defines several PrintWriter(OutputStream outputStream)
constructors. The ones shown next have PrintWriter(OutputStream outputStream,
been specified from the start: boolean flushOnNewline)
PrintWriter(Writer outputStream)

25
PrintStream(OutputStream PrintWriter(Writer outputStream, boolean
outputStream) flushOnNewline)
PrintStream(OutputStream
outputStream, boolean flushOnNewline) Here, outputStream specifies an open
PrintStream(OutputStream OutputStream that will receive output.
outputStream, boolean flushOnNewline, The flushOnNewline parameter controls
String charSet) whether the output buffer is
automatically flushed every time println(
), printf( ), or format( ) is called. If
flushOnNewline is true, flushing
automatically takes place. If false,
flushing is not automatic. Constructors
that do not specify the flushOnNewline
parameter do not automatically flush.

import java.io.FileOutputStream; import java.io.File;


import java.io.PrintStream; import java.io.PrintWriter;
public class PrintStreamTest{ public class PrintWriterExample {
public static void main(String public static void main(String[]
args[])throws Exception{ args) throws Exception {
FileOutputStream fout=new //Data to write on Console
FileOutputStream("D:\\testout.txt "); using PrintWriter
PrintStream pout=new PrintWriter writer = new
PrintStream(fout); PrintWriter(System.out);
pout.println(2016); writer.write("JAVA provides
pout.println("Hello Java"); tutorials of all technology.");
pout.println("Welcome to Java"); writer.flush();
pout.close(); writer.close();
fout.close(); //Data to write in File using
System.out.println("Success?"); PrintWriter
} PrintWriter writer1 =null;
} writer1 = new PrintWriter(new
File("D:\\testout.txt"));
Output: writer1.write("Like Java, Spring,
Hibernate, Android, PHP etc.");
Success... writer1.flush();
writer1.close();
The content of a text file testout.txt is set }
with the below data }

2016 Output:
Hello Java
Welcome to Java JAVA provides tutorials of all technology.

The content of a text file testout.txt is set


with the data Like Java, Spring,
Hibernate, Android, PHP etc.

26
Reading console Input and Writing Console Output:

In Java, there are three different ways for reading input from the user in the command
line environment(console).

1. Using Scanner Class


2. Using Buffered Reader Class
3. Using Console Class

Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to
parse primitive types and strings using regular expressions, however it is also can be used to read input
from the user in the command line.

// Java program to demonstrate working of Scanner in Java

import java.util.Scanner;

class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string "+s);

int a = in.nextInt();
System.out.println("You entered integer "+a);

float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}

Using Buffered Reader Class

27
In Java, console input is accomplished by reading from System.in. To obtain a
characterbased stream that is attached to the console, wrap System.in in a
BufferedReader object.

BufferedReader supports a buffered input stream. Its most commonly used


constructor is shown here:
BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that
is being created.
Reader is an abstract class. One of its concrete subclasses is InputStreamReader,
which converts bytes to characters.
To obtain an InputStreamReader object that is linked to System.in, use the following
constructor:

InputStreamReader(InputStream inputStream)

Because System.in refers to an object of type InputStream, it can be used for


inputStream.

Putting it all together, the following line of code creates a BufferedReader that is
connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

BufferedReader to read a charecter BufferedReader read all strings


To read a character from a To read a string from the keyboard, use
BufferedReader, use read( ). The version the version of readLine( ) that is a
of read( ) that we will be using is member of the BufferedReader class. Its
general form is shown here:
int read( ) throws IOException String readLine( ) throws IOException

read() method is used with As you can see, it returns a String


BufferedReader object to read object.
characters. As this function returns
integer type value has we need to use The following program demonstrates
typecasting to convert it into char type. BufferedReader and the readLine( )
method;

the program reads and displays lines of


text until you enter the word “stop”:

// Use a BufferedReader to read // Read a string from console using a


characters from the console. BufferedReader.
import java.io.*; import java.io.*;
class BRRead { class BRReadLines {
public static void main(String args[]) public static void main(String args[])
throws IOException throws IOException
{ {
char c;

28
BufferedReader br = new // create a BufferedReader using
BufferedReader(new System.in
InputStreamReader(System.in)); BufferedReader br = new
System.out.println("Enter characters, 'q' BufferedReader(new
to quit."); InputStreamReader(System.in));
// read characters String str;
do { System.out.println("Enter lines of text.");
c = (char) br.read(); System.out.println("Enter 'stop' to quit.");
System.out.println(c); do {
} while(c != 'q'); str = br.readLine();
} } while(!str.equals("stop"));
} }
}
Here is a sample run:

Enter characters, 'q' to quit.


123abcq
1
2
3
a
b
c
q
..

Using Console Class

➢ Java SE 6 adds the Console class. It is used to read from and write to
the console, if one exists.
➢ Console is primarily a convenience class because most of its
functionality is available through System.in and System.out.

Syntax:

Console supplies no constructors. Instead, a Console object is obtained by


calling System.console( ), which is shown here:

static Console console( )

If a console is available, then a reference to it is returned. Otherwise, null is


returned. A console will not be available in all cases. Thus, if null is returned,
no console I/O is possible

Here is an example that demonstrates the Console class:


// Demonstrate Console.

29
import java.io.*;
class ConsoleDemo {
public static void main(String args[]) {
String str;
Console con = System.console(); // Obtain a reference to the console.

str = con.readLine("Enter a string: "); // Read a string and then display it.

System.out.println(str);
}
}

Here is sample output:


Enter a string: This is a test.
Here is your string: This is a test.

RandomAccessFile

➢ RandomAccessFile encapsulates a random-access file. It is not derived


from InputStream or OutputStream.
➢ Instead, it implements the interfaces DataInput and DataOutput, which
define the basic I/O methods. It also implements the Closeable interface.
➢ RandomAccessFile is special because it supports positioning requests—
that is, you can position the file pointer within the file.
Syntax:
It has these two constructors:

RandomAccessFile(File fileObj, String access)


throws FileNotFoundException
or
RandomAccessFile(String filename, String access)
throws FileNotFoundException

• here fileObj specifies the name of the file to open as a File object.
• In the second form, the name of the file is passed in filename.
• In both cases, access determines what type of file access is permitted.
File Access parameter as:
• If it is “r”, then the file can be read, but not written.
• If it is “rw”, then the file is opened in read-write mode.

• If it is “rws”, the file is opened for read-write operations and every


change to the file’s data or metadata will be immediately written to the
physical device.

30
• If it is “rwd”, the file is opened for read-write operations and every change
to the file’s data will be immediately written to the physical device.

➢ The method seek( ), shown here, is used to set the current position of the
file pointer within the file:

void seek(long newPos) throws IOException

➢ It also includes some additional methods. One is setLength( ). It has this


signature:

void setLength(long len) throws IOException


RandomAccessFile read example RandomAccessFile write example
import java.io.*; import java.io.*;
public class randomacsess { public class randomrw {
public static void main(String public static void main(String
args[])throws Exception args[])throws Exception
{ {
RandomAccessFile raf = new RandomAccessFile raf = new
RandomAccessFile("C:\\Users\\mrcew\ RandomAccessFile("C:\\Users\\m
\Desktop\\iostreams\\input.txt", "r"); rcew\\Desktop\\iostreams\\inpu
trw.txt", "rw");
raf.seek(1); raf.seek(5);
raf.write("Data".getBytes());
byte[] bytes = new byte[50]; raf.close();
raf.read(bytes);
raf.close(); }
System.out.println(new String(bytes)); }

}
}

Java File Class


Java File class represents the files and directory pathnames in an abstract
manner. This class is used for creation of files and directories, file searching,
file deletion, etc.

Constructor Description
File(File parent, It creates a new File instance from a parent abstract
String child) pathname and a child pathname string.
It creates a new File instance by converting the given
File(String pathname)
pathname string into an abstract pathname.

31
File(String parent, It creates a new File instance from a parent pathname
String child) string and a child pathname string.
It creates a new File instance by converting the given
File(URI uri)
file: URI into an abstract pathname.

Syntax(Constructors):

File(String directoryPath) // directoryPath is the path name of the file

File(String directoryPath, String filename) //filename is the name of the file or


subdirectory

File(File dirObj, String filename) // dirObj is a File object that specifies a


directory

File(URI uriObj) //uriObj is a URI object that describes a file.

For example:

File f1 = new File("/");


File f2 = new File("/","abc.txt");
File f3 = new File(f1,"abc.txt");

File defines many methods that obtain the standard properties of a File object.

➢ getName( ) returns the name of the file,


➢ getParent( ) returns the name of the parent directory
➢ exists( ) returns true if the file exists, false if it does not.
➢ renameTo( ) is used for rename the file shown here:

boolean renameTo(File newName)

the filename specified by newName becomes the new name of the


invoking File object.

➢ delete( ) use to delete a directory if the directory is empty. delete( )


returns true if it deletes the file and false if the file cannot be removed.

Some more methods is shown by program as below:

// Demonstrate File.
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);

32
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not writeable");
p(f1.canRead() ? "is readable" : "is not readable");
p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
p(f1.isFile() ? "is normal file" : "might be a named pipe");
p(f1.isAbsolute() ? "is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}
Output:
File Name: COPYRIGHT
Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes

Reading data from File Writting data from File


import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
public class fileinput { public class fileinput {
public static void public static void
main(String[] args) main(String[] args)
throws throws
FileNotFoundException,IOExce FileNotFoundException,IOExce
ption ption
{ {
File file = new File file = new
File("abc.txt"); File("abc.txt");
BufferedReader br = new FileWriter fw=new
BufferedReader(new FileWriter(file,true);
FileReader(file));

33
String st; BufferedWriter bw = new
while ((st = br.readLine()) != BufferedWriter(fw);
null)
System.out.println(st); String st="Object Oriented
} Programing ";
bw.write(st);
} bw.close();
}}
Serialization

The Java facilities for serialization and deserialization have been designed so
that much of the work to save and restore the state of an object occurs
automatically.

Serialization is the process of writing the state of an object to a byte stream.


This is useful when you want to save the state of your program to a permanent
storage area (data storage device that retains data after power to that device is
shut off.), such as a file. At a later time, you may restore these objects by using
the process of deserialization.

However, these cases in which the programmer may need to have control over
these processes. For example, it may be desirable to use compression or
encryption techniques.

The following program illustrates how to use object serialization and


deserialization. It begins by instantiating an object of class MyClass. This
object has three instance variables that are of types String, int, and double.

While in Object serialization:

➢ A FileOutputStream is created that refers to a file named “serial,” and


an ObjectOutputStream is created for that file stream.
➢ The writeObject( ) method of ObjectOutputStream is then used to
serialize our object. The object output stream is flushed and closed.

While in Object deserialization:

➢ A FileInputStream is then created that refers to the file named “serial,”


and an ObjectInputStream is created for that file stream.
➢ The readObject( ) method of ObjectInputStream is then used to
deserialize our object. The object input stream is then closed.

Note that MyClass is defined to implement the Serializable interface. If


this is not done, a NotSerializableException is thrown.
import java.io.*;
public class SerializationDemo {

34
public static void main(String args[]) {
// Object serialization
try {
MyClass object1 = new MyClass("Hello", -7, 2.7e10);
System.out.println("object1: " + object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}
catch(IOException e) {
System.out.println("Exception during serialization: " + e);
System.exit(0);
}
// Object deserialization
try {
MyClass object2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2: " + object2);
}
catch(Exception e) {
System.out.println("Exception during deserialization: " + e);
System.exit(0);
}
}
}
class MyClass implements Serializable {
String s;
int i;
double d;
public MyClass(String s, int i, double d) {
this.s = s;
this.i = i;
this.d = d;
}
public String toString() {
return "s=" + s + "; i=" + i + "; d=" + d;
}
}

The output is shown here:


object1: s=Hello; i=-7; d=2.7E10
object2: s=Hello; i=-7; d=2.7E10

35
Enumerations
The java enum constants are static and final implicitly. It is available from JDK
1.5.
Enumeration is a list of named constants, and these Java enumerations define
a class type. By making enumerations into classes

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY,


TUESDAY,WEDNESDAY,THURSDAY, FRIDAY and SATURDAY) , directions
(NORTH, SOUTH, EAST and WEST) etc.

Java Enums can be thought of as classes that have fixed set of constants.
• enum improves type safety
• enum can be easily used in switch
• enum can be traversed
• enum can have fields, constructors and methods
• enum may implement many interfaces but cannot extend any class
because it internally extends Enum class

Example:

class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {

for (Season s : Season.values()) //The values() method returns an


array containing all the values of the enum.
System.out.println(s);

}}
Output:

WINTER
SPRING
SUMMER
FALL

Example of specifying initial value to the enum constants

class EnumExample4{

36
enum Season{
WINTER(5), SPRING(10), SUMMER(15), FALL(20);

private int value;


private Season(int value){
this.value=value;
}
}
public static void main(String args[]){
for (Season s : Season.values())
System.out.println(s+" "+s.value);

}}
Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20

AutoBoxing

The automatic conversion of primitive data types into its equivalent Wrapper
type is known as boxing and opposite operation is known as unboxing. This is
the new feature of Java5. So java programmer doesn't need to write the
conversion code.

No need of conversion between primitives and Wrappers manually so less


coding is required.

Example:
class BoxingExample1{
public static void main(String args[]){
int a=50;
Integer a2=new Integer(a);//Boxing

37
Integer a3=5;//Boxing

System.out.println(a2+" "+a3);
}
}
Output:50 5

Unboxing Example:
The automatic conversion of wrapper class type into corresponding primitive
type, is known as Unboxing. Let's see the example of unboxing:

class UnboxingExample1{
public static void main(String args[]){
Integer i=new Integer(50);
int a=i;

System.out.println(a);
}
}

Generics
The term generics means parameterized types. Parameterized types are
important because they enable you 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.

Thus, generics expand your ability to reuse code and let you do so safely and
easily.
The type parameters naming conventions are important to learn generics
thoroughly. The commonly type parameters are as follows:
1. T - Type
2. E - Element
3. K - Key
4. N - Number
5. V – Value
Generics Work Only with Objects

When declaring an instance of a generic type, the type argument passed to the
type parameter must be a class type. You cannot use a primitive type, such as
int or char.
For example, with Gen, it is possible to pass any class type to T, but you
cannot pass a primitive type to a type parameter.

ForExample:

38
class MyGen<T>
{
T obj;

void add(T obj)


{this.obj=obj;}

T get()
{return obj;}
}

public class genricDemo {


public static void main(String args[])
{
MyGen<Integer> m=new MyGen<Integer>();

m.add(2);
//m.add("vivek");//Compile time error
System.out.println(m.get());

Output:
2

Example 2 Example 3
public class testgeneric1 { Example3:
public static < E > void // A simple generic class with two
printArray(E[] elements) { type
for ( E element : elements){ // parameters: T and V.
System.out.println(element ); class TwoGen<T, V> {
} T ob1;
System.out.println(); V ob2;
} // Pass the constructor a reference to
public static void main( String // an object of type T and an object
args[] ) { of type V.
Integer[] intArray = { 10, 20, 30, TwoGen(T o1, V o2) {
40, 50 }; ob1 = o1;
Character[] charArray = { 'J', 'A', ob2 = o2;
'V', 'A', 'T','P','O','I','N','T' }; }
// Show types of T and V.
System.out.println( "Printing void showTypes() {
Integer Array" ); System.out.println("Type of T is " +
printArray( intArray ); ob1.getClass().getName());
System.out.println("Type of V is " +
ob2.getClass().getName());

39
System.out.println( "Printing }
Character Array" ); T getob1() {
printArray( charArray ); return ob1;
} }
} V getob2() {
Output: return ob2;
Printing Integer Array }
10
20 }
30 public class testgeneric2
40 {
50 public static void main(String
args[]) {
Printing Character Array
J TwoGen<Integer, String> tgObj =
A new TwoGen<Integer, String>(88,
V "Generics");
A // Show the types.
T tgObj.showTypes();
P
O // Obtain and show values.
I int v = tgObj.getob1();
N System.out.println("value: " + v);
T String str = tgObj.getob2();
System.out.println("value: " + str);
} }

}
Output:
Type of T is java.lang.Integer
Type of V is java.lang.String
value: 88
value: Generics

40

You might also like