[go: up one dir, main page]

0% found this document useful (0 votes)
141 views49 pages

Unit 5 Notes

Notes

Uploaded by

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

Unit 5 Notes

Notes

Uploaded by

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

StringTokenizer

 Parsing is the division of text into a set of discrete parts, or tokens, which in a certain
sequence can convey a semantic meaning
 StringTokenizer, specify an input string and a string that contains delimiters
 Delimiters are characters that separate tokens.
 The default set of delimiters consists of the whitespace characters: space, tab, newline, and
carriage return.
 StringTokenizer parse “key=value” pairs Consecutive sets of “key=value” pairs are
separated by a semicolon.
Constructors
 StringTokenizer(String str, String delimiters, boolean delimAsToken)
 str is the string that will be tokenized
 delimiters is a string that specifies the delimiters
 delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed

Methods
hasMoreTokens( )-returns true while there are more tokens to be extracted
int countTokens( )- Using the current set of delimiters, the method determines the number of tokens
left to be parsed and returns the result.
boolean hasMoreElements( )- Returns true if one or more tokens remain in the string and returns
false if there are none.
Object nextElement( )- Returns the next token as an Object.
Ex:
import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java: The Complete Reference;" +
"author=Schildt;" +
"publisher=Osborne/McGraw-Hill;" +
"copyright=2002";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
BitSet
 A BitSet class creates a special type of array that holds bit values.
 array can increase in size as needed.
 similar to a vector of bits
constructors
 BitSet(int size)
Methods
 void and(BitSet bitSet)- ANDs the contents of the invoking BitSet object with those
specified by bitSet. The result is placed into the invoking object.
 void andNot(BitSet bitSet)- For each 1 bit in bitSet, the corresponding bit in the invoking
BitSet is cleared
 int cardinality( )- Returns the number of set bits in the invoking object.
 void clear(int startIndex, int endIndex)- Zeros the bits from startIndex to endIndex–1.
 boolean equals(Object bitSet)- Returns true if the invoking bit set is equivalent to the one
passed in bitSet. Otherwise, the method returns false.

1
 BitSet get(int startIndex, int endIndex)- Returns a BitSet that consists of the bits from
startIndex to endIndex–1. The invoking object is not changed.
 boolean isEmpty( )- Returns true if all bits in the invoking object are zero.
 void xor(BitSet bitSet)- XORs the contents of the invoking BitSet object with that specified
by bitSet. The result is placed into the invoking object.
Ex:
import java.util.BitSet;
class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++) {
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
Output
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
Date class
The Date class encapsulates the current date and time.
The java.util.Date class implements Serializable, Cloneable and Comparable<Date> interface.
constructors:
Date( )- Creates a date object representing current date and time.
Date(long millisec)- Creates a date object for the given milliseconds since January 1, 1970, 00:00:00
GMT

2
Methods

Method Description

boolean after(Date date) tests if current date is after the given date.

boolean before(Date date) tests if current date is before the given date.

int compareTo(Date date) compares current date with given date.

boolean equals(Date date) compares current date with given date for equality.

static Date from(Instant instant) returns an instance of Date object from Instant date.

long getTime() returns the time represented by this date object.

void setTime(long time) changes the current date and time to given time.
Ex:
import java.util.Date;
class DateDemo {
public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();
// display time and date using toString()
System.out.println(date);
// Display number of milliseconds since midnight, January 1, 1970 GMT
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);
}
}
output
Mon Apr 22 09:51:52 CDT 2002
Milliseconds since Jan. 1, 1970 GMT = 1019487112894
Calendar Class

JCalendar class is an abstract class that provides methods for converting date between a specific
instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc.

It inherits Object class and implements the Comparable interface.

Calendar provides no public constructors.

Calendar defines several protected instance variables.

Method Description

public void add(int field, int Adds the specified (signed) amount of time to the given
amount) calendar field.

3
public boolean after (Object when) The method Returns true if the time represented by this
Calendar is after the time represented by when Object.

public boolean before(Object when) The method Returns true if the time represented by this
Calendar is before the time represented by when Object.

public final void clear(int field) Set the given calendar field value and the time value of this
Calendar undefined.

public int compareTo(Calendar The compareTo() method of Calendar class compares the time
anotherCalendar) values (millisecond offsets) between two calendar object.

public int getFirstDayOfWeek() Returns the first day of the week in integer form.

public final Date getTime() This method gets the time value of calendar object and
Returns date.

public long getTimeInMillis() Returns the current time in millisecond. This method has long
as return type.

public TimeZone getTimeZone() This method gets the TimeZone of calendar object and
Returns a TimeZone object.

public int getWeeksInWeekYear() Return total weeks in week year. Weeks in week year is
returned in integer form.

public void set(int field, int value) Sets the specified calendar field by the specified value.

public final void setTime(Date date) Sets the Time of current calendar object. A Date object id
passed as the parameter.

public void setTimeInMillis(long Sets the current time in millisecond.


millis)

public void setTimeZone(TimeZone Sets the TimeZone with passed TimeZone value (object) as
value) the parameter.
Ex:
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
output
The current date is : Thu Jan 19 18:47:02 IST 2017
15 days ago: Wed Jan 04 18:47:02 IST 2017
4 months later: Thu May 04 18:47:02 IST 2017

4
2 years later: Sat May 04 18:47:02 IST 2019

Random
The java.util.Random class instance is used to generate a stream of pseudorandom
numbers.Following are the important points about Random −
 The class uses a 48-bit seed, which is modified using a linear congruential formula.
 The algorithms implemented by class Random use a protected utility method that on each
invocation can supply up to 32 pseudorandomly generated bits.

constructors

Random()
This creates a new random number generator.
Random(long seed)
This creates a new random number generator using a single long seed.

Methods

Sr.No. Method & Description

1 protected int next(int bits)

This method generates the next pseudorandom number.

2 boolean nextBoolean()

This method returns the next pseudorandom, uniformly distributed boolean value from this
random number generator's sequence.

3 void nextBytes(byte[] bytes)

This method generates random bytes and places them into a user-supplied byte array.

4 double nextDouble()

This method returns the next pseudorandom, uniformly distributed double value between 0.0
and 1.0 from this random number generator's sequence.

5 float nextFloat()

This method returns the next pseudorandom, uniformly distributed float value between 0.0
and 1.0 from this random number generator's sequence.

6 double nextGaussian()

This method returns the next pseudorandom, Gaussian ("normally") distributed double value

5
with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

8 int nextInt(int n)

This method returns a pseudorandom, uniformly distributed int value between 0 (inclusive)
and the specified value (exclusive), drawn from this random number generator's sequence.

9 long nextLong()

This method returns the next pseudorandom, uniformly distributed long value from this
random number generator's sequence.

10 void setSeed(long seed)

This method sets the seed of this random number generator using a single long seed.

GregorianCalendar
The java.util.GregorianCalendar class is a concrete subclass of Calendar and provides the standard
calendar system used by most of the world.Following are the important points about
GregorianCalendar −
 It is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the
support of a single discontinuity, which corresponds by default to the Gregorian date when
the Gregorian calendar was instituted.
 The Julian calendar specifies leap years every four years, whereas the Gregorian calendar
omits century years which are not divisible by 400.

Constructors

Sr.No. Constructor & Description

1
GregorianCalendar()
This constructs a default GregorianCalendar using the current time in the default time zone
with the default locale.

2
GregorianCalendar(int year, int month, int dayOfMonth)
This constructs a GregorianCalendar with the given date set in the default time zone with the
default locale.

6
Methods

Sr.No. Method & Description

1 void add(int field, int amount)

This method adds the specified (signed) amount of time to the given calendar field, based on the
calendar's rules.

2 Object clone()

This method creates and returns a copy of this object.

3 protected void computeFields()

This method converts the time value (millisecond offset from the Epoch) to calendar field
values.

4 protected void computeTime()

This method converts calendar field values to the time value (millisecond offset from the
Epoch).

5 boolean equals(Object obj)

This method compares this GregorianCalendar to the specified Object.

6 int getActualMaximum(int field)

This method returns the maximum value that this calendar field could have, taking into
consideration the given time value and the current values of the getFirstDayOfWeek,
getMinimalDaysInFirstWeek, getGregorianChange and getTimeZone methods.

7 int getActualMinimum(int field)

This method returns the minimum value that this calendar field could have, taking into
consideration the given time value and the current values of the getFirstDayOfWeek,
getMinimalDaysInFirstWeek, getGregorianChange and getTimeZone methods.

8 int getGreatestMinimum(int field)

This method returns the highest minimum value for the given calendar field of this
GregorianCalendar instance.

9 Date getGregorianChange()

This method gets the Gregorian Calendar change date.

7
10 int getLeastMaximum(int field)

This method returns the lowest maximum value for the given calendar field of this
GregorianCalendar instance.

11 int getMaximum(int field)

This method returns the maximum value for the given calendar field of this GregorianCalendar
instance.

12 int getMinimum(int field)

This method returns the minimum value for the given calendar field of this GregorianCalendar
instance.

13 TimeZone getTimeZone()

This method gets the time zone.

14 int hashCode()

This method generates the hash code for this GregorianCalendar object.

15 boolean isLeapYear(int year)

This method determines if the given year is a leap year.

16 void roll(int field, boolean up)

This method adds or subtracts (up/down) a single unit of time on the given time field without
changing larger fields.

17 void roll(int field, int amount)

This method adds a signed amount to the specified calendar field without changing larger fields.

18 void setGregorianChange(Date date)

This method sets the GregorianCalendar change date.

19 setTimeZone(TimeZone zone)

This method sets the time zone with the given time zone value.

Byte Streams
 The byte stream classes provide a rich environment for handling byte-oriented I/O.
 A byte stream can be used with any type of object, including binary data.
 This versatility makes byte streams important to many types of programs.
InputStream
InputStream is an abstract class that defines Java’s model of streaming byte input. All of the
methods in this class will throw an IOException on error conditions.

8
Methods

Method Description

1) public abstract int reads the next byte of data from the input stream. It
read()throws IOException returns -1 at the end of the file.

2) public int returns an estimate of the number of bytes that can be


available()throws read from the current input stream.
IOException

3) public void close()throws is used to close the current input stream


IOException

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.

Methods
Method Description

1) public void write(int)throws is used to write a byte to the current output


IOException stream.

2) public void write(byte[])throws is used to write an array of byte to the current


IOException output stream.

3) public void flush()throws flushes the current output stream.


IOException

4) public void close()throws is used to close the current output stream.


IOException

FileInputStream

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.

9
Methods

int available() It is used to return the estimated number of bytes that can be read from
the input stream.

int read() It is used to read the byte of data from the input stream.

int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.

int read(byte[] b, int It is used to read up to len bytes of data from the input stream.
off, int len)

long skip(long x) It is used to skip over and discards x bytes of data from the input stream.

FileChannel It is used to return the unique FileChannel object associated with the file
getChannel() input stream.

FileDescriptor It is used to return the FileDescriptor object.


getFD()

protected void It is used to ensure that the close method is call when there is no more
finalize() reference to the file input stream.

void close() It is used to closes the stream.


Ex:
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);}
}
}
FileOutputStream Class

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

Method Description

protected void finalize() It is used to clean up the connection with the file output stream.

10
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.

void write(byte[] ary, int It is used to write len bytes from the byte array starting at
off, int len) offset off to the file output stream.

void write(int b) It is used to write the specified byte to the file output stream.

FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream.


Ex:
import java.io.FileOutputStream;
public class FileOutputStreamExample {
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);}
}
}

ByteArrayInputStream

Java ByteArrayInputStream class contains an internal buffer which is used to read byte array as
stream. the data is read from a byte array.

The buffer of ByteArrayInputStream automatically grows according to data.

Constructors

Constructor Description

ByteArrayInputStream(byte[] ary) Creates a new byte array input stream which


uses ary as its buffer array.

ByteArrayInputStream(byte[] ary, int Creates a new byte array input stream which
offset, int len) uses ary as its buffer array that can read up to
specified len bytes of data from an array.

11
Methods

Methods Description

int available() It is used to return the number of remaining bytes that can be
read from the input stream.

int read() It is used to read the next byte of data from the input stream.

boolean markSupported() It is used to test the input stream for mark and reset method.

long skip(long x) It is used to skip the x bytes of input from the input stream.

void mark(int It is used to set the current marked position in the stream.
readAheadLimit)

void reset() It is used to reset the buffer of a byte array.

void close() It is used for closing a ByteArrayInputStream.


Output

ASCII value of Character is:35; Special character is: #


ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &
ByteArrayOutputStream Class

Java ByteArrayOutputStream class is used to write common data into multiple files. In this stream,
the data is written into a byte array which can be written to multiple streams later.

The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams.

Constructors

Constructor Description

ByteArrayOutputStream() Creates a new byte array output stream with the initial
capacity of 32 bytes, though its size increases if necessary.

ByteArrayOutputStream(int Creates a new byte array output stream, with a buffer


size) capacity of the specified size, in bytes.

12
Methods

Method Description

void write(byte[] b, int off, It is used for writing len bytes from specified byte array starting
int len from the offset off to the byte array output stream.

void writeTo(OutputStream It is used for writing the complete content of a byte array output
out) stream to the specified output stream.

void reset() It is used to reset the count field of a byte array output stream to zero
value.

void close() It is used to close the ByteArrayOutputStream.

FilterInputStream Class

Java FilterInputStream class implements the InputStream. It contains different sub classes
as BufferedInputStream, DataInputStream for providing additional functionality.

Methods

Method Description

int available() It is used to return an estimate number of bytes that can be read from
the input stream.

int read() It is used to read the next byte of data from the input stream.

int read(byte[] b) It is used to read up to byte.length bytes of data from the input stream.

long skip(long n) It is used to skip over and discards n bytes of data from the input
stream.

boolean It is used to test if the input stream support mark and reset method.
markSupported()

void mark(int It is used to mark the current position in the input stream.
readlimit)

13
Ex:

import java.io.*;

public class FilterExample {

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

File data = new File("D:\\testout.txt");

FileInputStream file = new FileInputStream(data);

FilterInputStream filter = new BufferedInputStream(file);

int k =0;

while((k=filter.read())!=-1){

System.out.print((char)k);

file.close();

filter.close();

FilterOutputStream Class

Java FilterOutputStream class implements the OutputStream class. It provides different sub classes
such as BufferedOutputStream and DataOutputStream to provide additional functionality.

Methods

Method Description

void write(int b) It is used to write the specified byte to the output stream.

void write(byte[] ary) It is used to write ary.length byte to the output stream.

void write(byte[] b, int off, int It is used to write len bytes from the offset off to the output
len) stream.

14
void flush() It is used to flushes the output stream.

void close() It is used to close the output stream.

Ex:

import java.io.*;

public class FilterExample {

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

File data = new File("D:\\testout.txt");

FileOutputStream file = new FileOutputStream(data);

FilterOutputStream filter = new FilterOutputStream(file);

String s="Welcome to java.";

byte b[]=s.getBytes();

filter.write(b);

filter.flush();

filter.close();

file.close();

System.out.println("Success...");

BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer
mechanism to make the performance fast.

The important points about BufferedInputStream are:

o When the bytes from the stream are skipped or read, the internal buffer automatically refilled
from the contained input stream, many bytes at a time.
o When a BufferedInputStream is created, an internal buffer array is created.

15
Constructors

Constructor Description

BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it argument,


the input stream IS, for later use.

BufferedInputStream(InputStream IS, It creates the BufferedInputStream with a specified buffer


int size) size and saves it argument, the input stream IS, for later
use.

Methods

Method Description

int available() It returns an estimate number of bytes that can be read from the input
stream without blocking by the next invocation method for the input
stream.

int read() It read the next byte of data from the input stream.

int read(byte[] b, int It read the bytes from the specified byte-input stream into a specified
off, int ln) byte array, starting with the given offset.

void close() It closes the input stream and releases any of the system resources
associated with the stream.

void reset() It repositions the stream at a position the mark method was last called on
this input stream.

void mark(int readlimit) It sees the general contract of the mark method for the input stream.

long skip(long x) It skips over and discards x bytes of data from the input stream.

16
boolean It tests for the input stream to support the mark and reset methods.
markSupported()

Ex:

import java.io.*;

public class BufferedInputStreamExample{

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

BufferedInputStream bin=new BufferedInputStream(fin);

int i;

while((i=bin.read())!=-1){

System.out.print((char)i);

bin.close();

fin.close();

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

BufferedOutputStream Class -Java BufferedOutputStream class is used for buffering an output


stream. It internally uses buffer to store data. It adds more efficiency than to write data directly
into a stream.

Constructors

Constructor Description

BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is


used for writing the data to the specified output

17
stream.

BufferedOutputStream(OutputStream os, It creates the new buffered output stream which is


int size) used for writing the data to the specified output
stream with a specified buffer size.

Methods

Method Description

void write(int b) It writes the specified byte to the buffered output stream.

void write(byte[] b, int It write the bytes from the specified byte-input stream into a
off, int len) specified byte array, starting with the given offset

void flush() It flushes the buffered output stream.

Ex:

import java.io.*;

public class BufferedOutputStreamExample{

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

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

BufferedOutputStream bout=new BufferedOutputStream(fout);

String s="Welcome to java.";

byte b[]=s.getBytes();

bout.write(b);

bout.flush();

bout.close();

18
fout.close();

System.out.println("success");

PushbackInputStream Class

Java PushbackInputStream class overrides InputStream and provides extra functionality to another
input stream. It can unread a byte which is already read and push back one byte.

Methods
It is used to test if the input stream support mark and reset method.

Method Description

int available() It is used to return the number of bytes that can be read from the input
stream.

int read() It is used to read the next byte of data from the input stream.

boolean
markSupported()

void mark(int readlimit) It is used to mark the current position in the input stream.

long skip(long x) It is used to skip over and discard x bytes of data.

void unread(int b) It is used to pushes back the byte by copying it to the pushback buffer.

void unread(byte[] b) It is used to pushes back the array of byte by copying it to the
pushback buffer.

void reset() It is used to reset the input stream.

void close() It is used to close the input stream.

Ex:

19
import java.io.*;

public class InputStreamExample {

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

String srg = "1##2#34###12";

byte ary[] = srg.getBytes();

ByteArrayInputStream array = new ByteArrayInputStream(ary);

PushbackInputStream push = new PushbackInputStream(array);

int i;

while( (i = push.read())!= -1) {

if(i == '#') {

int j;

if( (j = push.read()) == '#'){

System.out.print("**");

}else {

push.unread(j);

System.out.print((char)i);

}else {

System.out.print((char)i);

PrintStream Class

The PrintStream class provides methods to write data to another stream. The
PrintStream class automatically flushes the data so there is no need to call flush() method. methods
don't throw IOException.

20
Method Description

void print(boolean b) It prints the specified boolean value.

void print(char c) It prints the specified char value.

void print(char[] c) It prints the specified character array values.

void print(int i) It prints the specified int value.

void print(long l) It prints the specified long value.

void print(float f) It prints the specified float value.

void print(double d) It prints the specified double value.

void print(String s) It prints the specified string value.

void print(Object obj) It prints the specified object value.

void println(boolean b) It prints the specified boolean value and terminates the line.

void println(char c) It prints the specified char value and terminates the line.

Ex:

import java.io.FileOutputStream;

import java.io.PrintStream;

public class PrintStreamTest{

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

FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");

PrintStream pout=new PrintStream(fout);

pout.println(2016);

pout.println("Hello Java");

pout.println("Welcome to Java");

pout.close();

21
fout.close();

System.out.println("Success?");

Character stream

classes provide sufficient functionality to handle any type of I/O operation

Reader
Reader is an abstract class for reading character streams.

Constructor

Modifier Constructor Description

protected Reader() It creates a new character-stream reader whose critical


sections will synchronize on the reader itself.

protected Reader(Object It creates a new character-stream reader whose critical


lock) sections will synchronize on the given object.

Methods

Modifier and Method Description


Type

abstract void close() It closes the stream and releases any


system resources associated with it.

Void mark(int It marks the present position in the stream.


readAheadLimit)

Boolean markSupported() It tells whether this stream supports the


mark() operation.

Int read() It reads a single character.

22
Int read(char[] cbuf) It reads characters into an array.

abstract int read(char[] cbuf, int off, It reads characters into a portion of an
int len) array.

Int read(CharBuffer target) It attempts to read characters into the


specified character buffer.

Boolean ready() It tells whether this stream is ready to be


read.

Void reset() It resets the stream.

Long skip(long n) It skips characters.

Example
import java.io.*;
public class ReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("file.txt");
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
reader.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}

Writer

It is an abstract class for writing to character streams

Constructor

Constructor Description

23
Writer() It creates a new character-stream writer whose critical sections will
synchronize on the writer itself.

Writer(Object It creates a new character-stream writer whose critical sections will


lock) synchronize on the given object.

Methods

Method Description

append(char c) It appends the specified character to this writer.

append(CharSequence csq) It appends the specified character sequence to this writer

append(CharSequence csq, int It appends a subsequence of the specified character


start, int end) sequence to this writer.

close() It closes the stream, flushing it first.

flush() It flushes the stream.

write(char[] cbuf) It writes an array of characters.

write(char[] cbuf, int off, int It writes a portion of an array of characters.


len)

write(int c) It writes a single character.

write(String str) It writes a string.

write(String str, int off, int len) It writes a portion of a string.

Ex:
import java.io.*;
public class WriterExample {
public static void main(String[] args) {
try {

24
Writer w = new FileWriter("output.txt");
String content = "I love my country";
w.write(content);
w.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
CharArrayReader Class

The CharArrayReader is composed of two words: CharArray and Reader. The CharArrayReader class
is used to read character array as a reader (stream). It inherits Reader class.

Methods

Method Description

int read() It is used to read a single character

int read(char[] b, int off, It is used to read characters into the portion of an array.
int len)

boolean ready() It is used to tell whether the stream is ready to read.

boolean markSupported() It is used to tell whether the stream supports mark() operation.

long skip(long n) It is used to skip the character in the input stream.

void mark(int It is used to mark the present position in the stream.


readAheadLimit)

void reset() It is used to reset the stream to a most recent mark.

void close() It is used to closes the stream.

Ex:

import java.io.CharArrayReader;

25
public class CharArrayExample{

public static void main(String[] ag) throws Exception {

char[] ary = { 'j', 'a', 'v', 'a'};

CharArrayReader reader = new CharArrayReader(ary);

int k = 0;

// Read until the end of a file

while ((k = reader.read()) != -1) {

char ch = (char) k;

System.out.print(ch + " : ");

System.out.println(k);

Output

j : 106

a : 97

v : 118

a : 97

CharArrayWriter Class

The CharArrayWriter class can be used to write common data to multiple files. This class
inherits Writer class. Its buffer automatically grows when data is written in this stream. Calling the
close() method on this object has no effect.

Methods

Method Description

int size() It is used to return the current size of the buffer.

char[] toCharArray() It is used to return the copy of an input data.

26
String toString() It is used for converting an input data to a string.

CharArrayWriter append(char c) It is used to append the specified character to the


writer.

CharArrayWriter append(CharSequence csq) It is used to append the specified character


sequence to the writer.

CharArrayWriter append(CharSequence csq, It is used to append the subsequence of a specified


int start, int end) character to the writer.

void write(int c) It is used to write a character to the buffer.

void write(char[] c, int off, int len) It is used to write a character to the buffer.

void write(String str, int off, int len) It is used to write a portion of string to the buffer.

void writeTo(Writer out) It is used to write the content of buffer to different


character stream.

void flush() It is used to flush the stream.

void reset() It is used to reset the buffer.

void close() It is used to close the stream.

Ex:

import java.io.CharArrayWriter;

import java.io.FileWriter;

public class CharArrayWriterExample {

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

CharArrayWriter out=new CharArrayWriter();

out.write("Welcome to java");

27
FileWriter f1=new FileWriter("D:\\a.txt");

FileWriter f2=new FileWriter("D:\\b.txt");

FileWriter f3=new FileWriter("D:\\c.txt");

FileWriter f4=new FileWriter("D:\\d.txt");

out.writeTo(f1);

out.writeTo(f2);

out.writeTo(f3);

out.writeTo(f4);

f1.close();

f2.close();

f3.close();

f4.close();

System.out.println("Success...");

Output

a.txt:

Welcome to java

b.txt:

Welcome to java

c.txt:

Welcome to java

d.txt:

Welcome to java

FileReader Class

Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.

Constructors

28
Constructor Description

FileReader(String It gets filename in string. It opens the given file in read mode. If file doesn't
file) exist, it throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.

Methods

Method Description

int read() It is used to return a character in ASCII form. It returns -1 at the end of file.

void close() It is used to close the FileReader class.

Ex:

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

29
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.No need to convert string into byte array because it provides
method to write string directly.

Constructors

Constructor Description

FileWriter(String file) Creates a new file. It gets file name in string.

FileWriter(File file) Creates a new file. It gets file name in File object.

Methods

Method Description

void write(String text) It is used to write the string into FileWriter.

void write(char c) It is used to write the char into FileWriter.

void write(char[] c) It is used to write char array into FileWriter.

void flush() It is used to flushes the data of FileWriter.

void close() It is used to close the FileWriter.

Ex:

import java.io.FileWriter;

public class FileWriterExample {

public static void main(String args[]){

try{

30
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...");

BufferedReader Class

Java BufferedReader class is used to read the text from a character-based input stream. It can be used
to read data line by line by readLine() method. It makes the performance fast.

Constructors

Constructor Description

BufferedReader(Reader rd) It is used to create a buffered character input stream that


uses the default size for an input buffer.

BufferedReader(Reader rd, It is used to create a buffered character input stream that


int size) uses the specified size for an input buffer.

Methods

Method Description

int read() It is used for reading a single character.

int read(char[] cbuf, int It is used for reading characters into a portion of an array.
off, int len)

boolean markSupported() It is used to test the input stream support for the mark and
reset method.

31
String readLine() It is used for reading a line of text.

boolean ready() It is used to test whether the input stream is ready to be read.

long skip(long n) It is used for skipping the characters.

void reset() It repositions the stream at a position the mark method was
last called on this input stream.

void mark(int It is used for marking the present position in a stream.


readAheadLimit)

void close() It closes the input stream and releases any of the system
resources associated with the stream.

Ex:

import java.io.*;

public class BufferedReaderExample {

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

FileReader fr=new FileReader("D:\\testout.txt");

BufferedReader br=new BufferedReader(fr);

int i;

while((i=br.read())!=-1){

System.out.print((char)i);

br.close();

fr.close();

32
BufferedWriter Class

Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance
fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of
single arrays, characters, and strings.

Constructors

Constructor Description

BufferedWriter(Writer wrt) It is used to create a buffered character output stream that uses the
default size for an output buffer.

BufferedWriter(Writer wrt, int It is used to create a buffered character output stream that uses the
size) specified size for an output buffer.

Methods

Method Description

void newLine() It is used to add a new line by writing a line separator.

void write(int c) It is used to write a single character.

void write(char[] cbuf, int off, int len) It is used to write a portion of an array of characters.

void write(String s, int off, int len) It is used to write a portion of a string.

void flush() It is used to flushes the input stream.

void close() It is used to closes the input stream

Ex:

import java.io.*;

public class BufferedWriterExample {

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

33
FileWriter writer = new FileWriter("D:\\testout.txt");

BufferedWriter buffer = new BufferedWriter(writer);

buffer.write("Welcome to java.");

buffer.close();

System.out.println("Success");

PushbackReader Class

Java PushbackReader class is a character stream reader. It is used to pushes back a character into
stream and overrides the FilterReader class.

Methods
Method Description

int read() It is used to read a single character.

void mark(int It is used to mark the present position in a stream.


readAheadLimit)

boolean ready() It is used to tell whether the stream is ready to be read.

boolean markSupported() It is used to tell whether the stream supports mark() operation.

long skip(long n) It is used to skip the character.

void unread (int c) It is used to pushes back the character by copying it to the
pushback buffer.

void unread (char[] cbuf) It is used to pushes back an array of character by copying it to
the pushback buffer.

void reset() It is used to reset the stream.

34
void close() It is used to close the stream.

import java.io.*;

public class ReaderExample{

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

char ary[] = {'1','-','-','2','-','3','4','-','-','-','5','6'};

CharArrayReader reader = new CharArrayReader(ary);

PushbackReader push = new PushbackReader(reader);

int i;

while( (i = push.read())!= -1) {

if(i == '-') {

int j;

if( (j = push.read()) == '-'){

System.out.print("#*");

}else {

push.unread(j); // push back single character

System.out.print((char)i);

}else {

System.out.print((char)i);

PrintWriter class

Java PrintWriter class is the implementation of Writer class. It is used to print the formatted
representation of objects to the text-output stream.

Methods

35
Method Description

void println(boolean x) It is used to print the boolean value.

void println(char[] x) It is used to print an array of characters.

void println(int x) It is used to print an integer.

PrintWriter append(char c) It is used to append the specified character to the


writer.

PrintWriter append(CharSequence It is used to append the specified character sequence


ch) to the writer.

PrintWriter append(CharSequence It is used to append a subsequence of specified


ch, int start, int end) character to the writer.

boolean checkError() It is used to flushes the stream and check its error
state.

protected void setError() It is used to indicate that an error occurs.

protected void clearError() It is used to clear the error state of a stream.

PrintWriter format(String format, It is used to write a formatted string to the writer


Object... args) using specified arguments and format string.

void print(Object obj) It is used to print an object.

void flush() It is used to flushes the stream.

void close() It is used to close the stream.

import java.io.File;

36
import java.io.PrintWriter;

public class PrintWriterExample {

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

//Data to write on Console using PrintWriter

PrintWriter writer = new PrintWriter(System.out);

writer.write("Java provides tutorials of all technology.");

writer.flush();

writer.close();

//Data to write in File using PrintWriter

PrintWriter writer1 =null;

writer1 = new PrintWriter(new File("D:\\testout.txt"));

writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");

writer1.flush();

writer1.close();

Stream tokenizer

Java.io.StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens
to be read one at a time. The stream tokenizer can recognize identifiers, numbers, quoted strings, and
various comment styles.

Class declaration

Following is the declaration for Java.io.StreamTokenizer class −


public class StreamTokenizer
extends Object

Field

Following are the fields for Java.io.StreamTokenizer class −


 double nval − If the current token is a number, this field contains the value of that number.
 String sval − If the current token is a word token, this field contains a string giving the
characters of the word token.
 static int TT_EOF − A constant indicating that the end of the stream has been read.
 static int TT_EOL − A constant indicating that the end of the line has been read.

37
 static int TT_NUMBER − A constant indicating that a number token has been read.
 static int TT_WORD − A constant indicating that a word token has been read.
 int ttype − After a call to the nextToken method, this field contains the type of the token just
read.

Class constructors

Constructor & Description

StreamTokenizer(Reader r)
This creates a tokenizer that parses the given character stream.

Class methods

Method & Description

void eolIsSignificant(boolean flag)


This method determines whether or not ends of line are treated as tokens.

int nextToken()
This method parses the next token from the input stream of this tokenizer.

void whitespaceChars(int low, int hi)


This method specifies that all characters c in the range low <= c <= high are white space
characters.

void wordChars(int low, int hi)


This method specifies that all characters c in the range low <= c >= high are word
constituents.

Ex:

import java.io.*;

public class NewClass

public static void main(String[] args) throws InterruptedException,

FileNotFoundException, IOException

38
{

FileReader reader = new FileReader("ABC.txt");

BufferedReader bufferread = new BufferedReader(reader);

StreamTokenizer token = new StreamTokenizer(bufferread);

// Use of commentChar() method

token.commentChar('a');

int t;

while ((t = token.nextToken()) != StreamTokenizer.TT_EOF)

switch (t)

case StreamTokenizer.TT_NUMBER:

System.out.println("Number : " + token.nval);

break;

case StreamTokenizer.TT_WORD:

System.out.println("Word : " + token.sval);

break;

‘ABC’ file contains :


Programmers
1
2
3
goodmorning
Hello
Output:
Word : Programmers
Number : 1.0

39
Number : 2.0
Number : 3.0
Word : good morning
Word : Hello
Serialization

Java provides a mechanism, called 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.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods
for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one
method in particular stands out −

public final void writeObject(Object x) throws IOException

The ObjectInputStream class contains the following method for deserializing an object −

public final Object readObject() throws IOException, ClassNotFoundException

This method retrieves the next Object out of the stream and deserializes it. The return value is Object,
so you will need to cast it to its appropriate data type.

Example

public class Employee implements java.io.Serializable {

public String name;

public String address;

public transient int SSN;

public int number;

public void mailCheck() {

System.out.println("Mailing a check to " + name + " " + address);

Notice that for a class to be serialized successfully, two conditions must be met −

40
 The class must implement the java.io.Serializable interface.
 All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.

Serializing an Object

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program
instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does not
generate any output, but study the code and try to determine what the program is doing.

Note − When serializing an object to a file, the standard convention in Java is to give the file a
.ser extension.

Example

import java.io.*;

public class SerializeDemo {

public static void main(String [] args) {

Employee e = new Employee();

e.name = "Reyan Ali";

e.address = "Phokka Kuan, Ambehta Peer";

e.SSN = 11122333;

e.number = 101;

try {

FileOutputStream fileOut =

new FileOutputStream("/tmp/employee.ser");

ObjectOutputStream out = new ObjectOutputStream(fileOut);

out.writeObject(e);

out.close();

fileOut.close();

System.out.printf("Serialized data is saved in /tmp/employee.ser");

41
} catch (IOException i) {

i.printStackTrace();

Deserializing an Object

Example

import java.io.*;

public class DeserializeDemo {

public static void main(String [] args) {

Employee e = null;

try {

FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");

ObjectInputStream in = new ObjectInputStream(fileIn);

e = (Employee) in.readObject();

in.close();

fileIn.close();

} catch (IOException i) {

i.printStackTrace();

return;

} catch (ClassNotFoundException c) {

System.out.println("Employee class not found");

c.printStackTrace();

return;

System.out.println("Deserialized Employee...");

42
System.out.println("Name: " + e.name);

System.out.println("Address: " + e.address);

System.out.println("SSN: " + e.SSN);

System.out.println("Number: " + e.number);

Output

Deserialized Employee...

Name: Reyan Ali

Address:Phokka Kuan, Ambehta Peer

SSN: 0

Number:101

Here are following important points to be noted −

The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject()
method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the
class. If the JVM can't find a class during the deserialization of an object, it throws a
ClassNotFoundException.

Generic

Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods, or with a single class declaration, a set of related types,
respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.
Using Java Generic concept, we might write a generic method for sorting an array of objects, then
invoke the generic method with Integer arrays, Double arrays, String arrays and so on, to sort the
array elements.
Generic Classes
A generic class declaration looks like a non-generic class declaration, except that the class name is
followed by a type parameter section.
As with generic methods, the type parameter section of a generic class can have one or more type
parameters separated by commas. These classes are known as parameterized classes or parameterized
types because they accept one or more parameters.

Example

43
public class Box<T> {
private T t;

public void add(T t) {


this.t = t;
}

public T get() {
return t;
}

public static void main(String[] args) {


Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();

integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));

System.out.printf("Integer Value :%d\n\n", integerBox.get());


System.out.printf("String Value :%s\n", stringBox.get());
}
}

Output
Integer Value :10
String Value :Hello World

Generic Methods

 All generic method declarations have a type parameter section delimited by angle brackets (<
and >) that precedes the method's return type ( < E > in the next example).
 Each type parameter section contains one or more type parameters separated by commas. A
type parameter, also known as a type variable, is an identifier that specifies a generic type
name.
 The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
 A generic method's body is declared like that of any other method. Note that type parameters
can represent only reference types, not primitive types (like int, double and char).

44
Ex:
public class GenericMethodTest {

// generic method printArray

public static < E > void printArray( E[] inputArray ) {

// Display array elements

for(E element : inputArray) {

System.out.printf("%s ", element);

System.out.println();

public static void main(String args[]) {

// Create arrays of Integer, Double and Character

Integer[] intArray = { 1, 2, 3, 4, 5 };

Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };

Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

System.out.println("Array integerArray contains:");

printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");

printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");

printArray(charArray); // pass a Character array

Output

Array integerArray contains:

45
12345

Array doubleArray contains:

1.1 2.2 3.3 4.4

Array characterArray contains:

HELLO

Generic Interfaces
Generics also work with interfaces. Generic interfaces are specified just like generic classes. For
example :

The MyInterface is a generic interface that declares the method called myMethod( ). In general, a
generic interface is declared in the same way as is a generic class. In this case, the type parameter is T.
Next, MyInterface is implemented by MyClass. Myclass is a non generic class. if a class implements
a specific type of generic interface, then the implementing class does not need to be generic.

Advantage of Java Generics

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other
objects.

Without Generics, we can store any type of objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The
good programming strategy says it is far better to handle the problem at compile time than runtime.

File Class

The File class is an abstract representation of file and directory pathname. A pathname can be either
absolute or relative.

The File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory etc.

46
Constructor Description

File(File parent, String It creates a new File instance from a parent abstract
child) pathname and a child pathname string.

File(String pathname) It creates a new File instance by converting the given


pathname string into an abstract pathname.

File(String parent, It creates a new File instance from a parent pathname string
String child) and a child pathname string.

File(URI uri) It creates a new File instance by converting the given file:
URI into an abstract pathname.

Modifier Method Description


and Type

static createTempFile(String It creates an empty file in the default


File prefix, String suffix) temporary-file directory, using the given prefix
and suffix to generate its name.

Boolean createNewFile() It atomically creates a new, empty file named


by this abstract pathname if and only if a file
with this name does not yet exist.

Boolean canWrite() It tests whether the application can modify the


file denoted by this abstract pathname.String[]

Boolean canExecute() It tests whether the application can execute the


file denoted by this abstract pathname.

Boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.

Boolean isAbsolute() It tests whether this abstract pathname is


absolute.

Boolean isDirectory() It tests whether the file denoted by this abstract


pathname is a directory.

47
Boolean isFile() It tests whether the file denoted by this abstract
pathname is a normal file.

String getName() It returns the name of the file or directory


denoted by this abstract pathname.

String getParent() It returns the pathname string of this abstract


pathname's parent, or null if this pathname
does not name a parent directory.

Path toPath() It returns a java.nio.file.Path object constructed


from the this abstract path.

URI toURI() It constructs a file: URI that represents this


abstract pathname.

File[] listFiles() It returns an array of abstract pathnames


denoting the files in the directory denoted by
this abstract pathname

Long getFreeSpace() It returns the number of unallocated bytes in


the partition named by this abstract path name.

String[] list(FilenameFilter It returns an array of strings naming the files


filter) and directories in the directory denoted by this
abstract pathname that satisfy the specified
filter.

Boolean mkdir() It creates the directory named by this abstract


pathname.

Ex:

import java.io.*;

public class FileDemo {

public static void main(String[] args) {

try {

File file = new File("javaFile123.txt");

48
if (file.createNewFile()) {

System.out.println("New File is created!");

} else {

System.out.println("File already exists.");

} catch (IOException e) {

e.printStackTrace();

} }

output

New File is created!

49

You might also like