0% found this document useful (0 votes)
2 views

CH-6. File Java_notes.

Uploaded by

Aditya Sawant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

CH-6. File Java_notes.

Uploaded by

Aditya Sawant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Ch-6 Managing Input/Outputs Files in Java Marks: 08

Stream classes

Definition: The java. Io package contain a large number of stream classes that
provide capabilities for processing all types of data. These classes may be
categorized into two groups based on the data type on which they operate.
 Byte stream classes that provide support for handling I/O operations on bytes.
 Character stream classes that provide support for managing I/O operations on
characters.
Character Stream Class can be used to read and write 16-bit Unicode characters.
There are two kinds of character stream classes, namely, reader stream classes and
writer stream classes.

Q. Bytestream Class

 Byte streams class: It handles I/O operations on bytes. InputStream and


OutputStream classes are operated on bytes for reading and writing,
respectively.
 Byte streams are used in a program to read and write 8-bit bytes. InputStream
and OutputStream are the abstract super classes of all byte streams that have
a sequential nature. The stream is unidirectional; they can transmit bytes in
only one direction.
 InputStream and OutputStream provide the Application program Interface
(API) and partial implementation for input streams (streams that read bytes)
and output streams (streams that write bytes).

Input Stream Classes:


 java.io.InputStream is an abstract class that contains the basic methods for
reading raw bytes of data from a stream.
 The InputStream class defines methods for performing the input functions like:
reading bytes, closing streams, marking positions in streams, skipping ahead
in a stream and finding the number of bytes in a stream.

Page 1
InputStream class hierarchy

Input stream class methods:

1. int read ()- Returns an integer representation of next available byte of input.-
1 is returned at the stream end.
2. int read (byte buffer[ ])- Read up to buffer.length bytes into buffer & returns
actual number of bytes that are read. At the end returns –1.
3. int read(byte buffer[ ], int offset, int numbytes)- Attempts to read up to
numbytes bytes into buffer starting at buffer[offset]. Returns actual number of
bytes that are read. At the end returns –1.
4. void close()- to close the input stream
5. void mark(int numbytes)- places a mark at current point in input stream
and remain valid till number of bytes are read.
6. void reset()- Resets pointer to previously set mark/ goes back to stream
beginning.
7. long skip(long numbytes)- skips number of bytes.
8. int available()- Returns number of bytes currently available for reading.

Output Stream Classes:


 The java.io.OutputStream class sends raw bytes of data to a target such as
the console or a network server. Like InputStream, OutputStream is an
abstract class.
 The OutputStream includes methods that perform operations like: writing
bytes, closing streams, flushing streams etc.

Page 2
OutputStream class hierarchy

Methods defines by the OutputStream class are

1. void close() - to close the OutputStream


2. void write (int b) - Writes a single byte to an output stream.
3. void write(byte buffer[ ]) - Writes a complete array of bytes to an output
stream.
4. void write (byte buffer[ ], int offset, int numbytes) - Writes a sub range
of numbytes bytes from the array buffer, beginning at buffer[offset].
5. void flush() - clears the buffer.

Character streams Class


 It provides support for managing I/O operations on characters. Classes Reader
and Writer are operated on characters for reading and writing, respectively.
 Character streams can be used to read and write 16-bit Unicode characters.
Reader stream classes are designed to read character from the files and writer
stream classes are designed to perform all output operations on files.
 The primary advantage of character streams is that they make it easy to write
programs that are not dependent upon a specific character encoding, and are
therefore easy to internationalize.

Reader Stream Classes:


 Reader stream classes are designed to read character from the files. Reader is
designed to handle characters; therefore reader classes can perform all the
functions implemented by the input stream classes.

Page 3
Hierarchy of reader stream classes
Methods in Reader Class:

1. int read ()- Returns an integer representation of next available character


from invoking stream. -1 is returned at the stream end.
2. int read (char buffer[ ])- Read up to buffer.length chacters to buffer &
returns actual number of characters that are successfully read. At the end
returns –1.
3. int read(char buffer[ ], int offset, int numchars)- Attempts to read up to
numchars into buffer starting at buffer[offset]. Returns actual number of
characters that are read. At the end returns –1.
4. void close()- to close the input stream
5. void mark(int numchars)- places a mark at current point in input stream
and remain valid till number of characters are read.
6. void reset()- Resets pointer to previously set mark/ goes back to stream
beginning.
7. long skip(long numchars)- skips number of characters.
8. int available()- Returns number of bytes currently available for reading.

Writer Stream Classes:


 The Writer stream classes are designed to perform all output operations on
files. It is an output character stream that writes a sequence of Unicode
characters.

Hierarchy of writer stream classes

Page 4
All the methods in Writer class returns a void value and throws an IOException.
The methods are:

1. void close() - to close the OutputStream


2. void write (int ch) - Writes a single character to an output stream.
3. void write(char buffer[ ]) - Writes a complete array of characters to an
output stream.
4. void write (char buffer[ ], int offset, int numchars) - Writes a sub range
of numchars from the array buffer, beginning at buffer[offset].
5. void write(String str)- Writes str to output stream.
6. void write(String str, int offset, int numchars)- Writes a subrange of
numchars from string beginning at offset.
7. void flush() - clears the buffer.

Difference between Byte Stream Classes and Character Stream Classes:

Byte Stream Class Character Stream Class


Byte streams access the file byte by A character stream will read a file
byte (8 bits). character by character (16 bits).
Byte stream classes are classified Character stream classes are
into: classified into:
1. Input Stream Classes 1. Reader class
2. Output Stream Classes 2. Writer class
InputStream/OutputStream class is The Reader/Writer class is character-
byte-oriented. oriented.

The methods for byte streams The methods for character streams
generally work with byte data type. generally accept parameters of data
type char parameters.
Byte-stream classes end with the Character-stream classes end with
suffix InputStream and the suffix Reader or Writer.
OutputStream.

Page 5
It is possible to translate character It is possible to translate byte stream
stream into byte stream with into a character stream with
OutputStreamWriter. InputStreamReader.
Byte streams specifically used for The advantage of character streams,
reading and writing data in byte that is make it easy to write
format. programs, which is not dependent
upon a specific character encoding.
No conversion needed. Character streams convert the
underlying data bytes to Unicode,
which is a costly operation.
InputStream and OutputStream are Reader and Writer uses Unicode,
used for reading or writing binary hence they can be internationalized.
data. Hence in some cases they are more
efficient than byte streams.

Q. Distinguish between: (i) input stream and reader classes (ii) output
stream and writer classes.

Differentiate between Input Stream class and Reader Class

Input Stream Class Reader Class


Input Streams are used to read bytes Reader classes are used to read
from a stream. character streams.
Input Stream class useful for binary Reader classes are best used to read
data such as images, video and character data.
serialized objects.
Input Stream classes are used to read Reader class is used to read 16 bit
8 bit bytes. Unicode character stream.
An Input Stream is byte-oriented. A Reader is character-oriented.
Constructor: InputStream() Constructor: Reader() and
Reader(Object lock)
Methods: read(); Methods: read();
read(byte[] b); read(char[] buf);
read(byte[] b, int off, int read(char[] buf, int off, int
len); len);

Page 6
read(charBuffer dest);

Differentiate between Output Stream class and Writer class

Output Stream Class Writer Class


Output Streams are used to write Writer classes are used to writes
bytes to stream. character streams
An Output Stream is byte-oriented. A Writer is character-oriented.
OutputStream classes are used to Writer class is used to write 16 bit
write 8 bit bytes. Unicode character stream.
Constructor: OutputStream(); Constructor: Writer(); and
Writer(Object lock);
Methods: write(byte[] b); Methods: write(char[] buf);
write(byte[] b, int off, int write(char[] buf, int off, int
len); len);
write(int b); write(int c);
write(String str);
write(String str, int off, int
len);

Serialization with stream classes.

 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 persistent
storage area, such as a file.
 At a later time, you may restore these objects by using the process of
deserialization.
 Serialization is also needed to implement Remote Method Invocation (RMI).
RMI allows a Java object on one machine to invoke a method of a Java object
on a different machine.
 An object may be supplied as an argument to that remote method. The
sending machine serializes the object and transmits it. The receiving machine
deserializes it.
Example:

Page 7
 Assume that an object to be serialized has references to other objects,
which, in turn, have references to still more objects. This set of objects and
the relationships among them form a directed graph. There may also be
circular references within this object graph.
 That is, object X may contain a reference to object Y, and object Y may
contain a reference back to object X. Objects may also contain references
to themselves.
 The object serialization and deserialization facilities have been designed to
work correctly in these scenarios. If you attempt to serialize an object at
the top of an object graph, all of the other referenced objects are
recursively located and serialized.
 Similarly, during the process of deserialization, all of these objects and
their references are correctly restored.

Methods of file and file input stream class each.

File class Methods:

Method Description
public String getName() Returns the name of the file or directory denoted by
this abstract pathname.
public String Returns the pathname string of this abstract
getParent() pathname's parent, or null if this pathname does
not name a parent directory.
public String getPath() Converts this abstract pathname into a pathname
string.
public boolean Tests whether this abstract pathname is absolute.
isAbsolute() Returns true if this abstract pathname is absolute,
false otherwise
public boolean exists() Tests whether the file or directory denoted by this
abstract pathname exists. Returns true if and only if
the file or directory denoted by this abstract
pathname exists; false otherwise
public boolean Tests whether the file denoted by this abstract
isDirectory() pathname is a directory. Returns true if and only if
the file denoted by this abstract pathname exists
Page 8
and is a directory; false otherwise.
public boolean isFile() Tests whether the file denoted by this abstract
pathname is a normal file. A file is normal if it is not
a directory and, in addition, satisfies other system-
dependent criteria. Any non-directory file created by
a Java application is guaranteed to be a normal file.
Returns true if and only if the file denoted by this
abstract pathname exists and is a normal file; false
otherwise.

FileInputStream class methods:

Method Description
int available() Returns an estimate of the number of remaining
bytes that can be read (or skipped over) from this
input stream without blocking by the next
invocation of a method for this input stream.
void close() Closes this file input stream and releases any
system resources associated with the stream.
int read() Reads a byte of data from this input stream.
int read(byte[] b) Reads up to b.length bytes of data from this input
stream into an array of bytes.
read(byte[] b, int off, Reads up to len bytes of data from this input stream
int len) into an array of bytes.

Q. State syntax and describe any two methods of map class.


 The Map Classes Several classes provide implementations of the map
interfaces. A map is an object that stores associations between keys and
values, or key/value pairs.
 Given a key, you can find its value. Both keys and values are objects. The keys
must be unique, but the values may be duplicated. Some maps can accept a
null key and null values, others cannot.
Methods:
 void clear // removes all of the mapping from map
Page 9
 booleancontainsKey(Object key) //Returns true if this map contains a
mapping for the specified key.
 Boolean conainsValue(Object value)// Returns true if this map maps one or
more keys to the specified value
 Boolean equals(Object o) //Compares the specified object with this map for
equality.

Q. What is use of ArrayList Class ?State any three methods with their use
from ArrayList.

Use of ArrayList class:


1. ArrayList supports dynamic arrays that can grow as needed.
2. ArrayList is a variable-length array of object references. That is, an ArrayListcan
dynamically increase or decrease in size. Array lists are created with an initial size.
When this size is exceeded, the collection is automatically enlarged. When objects
are removed, the array may be shrunk.

Constructor for ArrayList class:


ArrayList():This constructor is used to create an empty list with an initial capacity
sufficient to hold 10 elements.
ArrayList(Collection c): This constructor is used to create a list containing the
elements of the specified collection.
ArrayList(int initialCapacity): This constructor is used to create an empty list with
an initial capacity.

Methods of ArrayList
Methods Description
boolean add(E e) This method appends the specified element to the end of
this list.
void add(int index, E This method inserts the specified element at the specified
element) position in this list.
boolean This method appends all of the elements in the specified
addAll(Collection c) collection to the end of this list, in the order that they are
returned by the specified collection's Iterator

Page 10
boolean addAll(int This method inserts all of the elements in the specified
index, Collection c) collection into this list, starting at the specified position.
void clear() This method removes all of the elements from this list.
boolean This method returns true if this list contains the specified
contains(Object o) element.
void This increases the capacity of this ArrayList.
ensureCapacity(int
minCapacity)
E get(int index) This method returns the element at the specified position in
this list.
int indexOf(Object o) This method returns the index of the first occurrence of the
specified element in this list, or -1 if this list does not
contain the element.
boolean isEmpty() This method returns true if this list contains no elements.
int lastIndexOf(Object This method returns the index of the last occurrence of the
o) specified element in this list, or -1 if this list does not
contain the element.
E remove(int index) This method removes the element at the specified position
in this list.
boolean This method removes the first occurrence of the specified
remove(Object o) element from this list, if it is present.
protected void This method removes from this list all of the elements
removeRange(int whose index is between fromIndex(inclusive) and
fromIndex, int toIndex) toIndex(exclusive).
E set(int index, E This method replaces the element at the specified position
element) in this list with the specified element.
int size() This method returns the number of elements in this list.
Object[] toArray() This method returns an array containing all of the elements
in this list in proper sequence (from first to last element).

Example program to implement ArrayList:


import java.util.*;

public class ArrayListDemo {


public static void main(String args[]) {
// create an array list

Page 11
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
System.out.println("Index of B:"+al.indexOf("B"));

}
}
Output:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Index of B:3

Q. Explain Date class

Date Class: Java provides the Date class available in java.util package, this class
encapsulates the current date and time.
Constructors
Page 12
 Date() : Allocates a Date object and initializes it so that it represents the time
at which it was allocated, measured to the nearest millisecond.
 Date(int year, int month, int date)
 Date(int year, int month, int date, int hrs, int min)
 Date(int year, int month, int date, int hrs, int min, int sec)
 Date(long date): Allocates a Date object and initializes it to represent the
specified number of milliseconds since the standard base time known as "the
epoch", namely January 1, 1970, 00:00:00 GMT.
 Date(String s)

Java Date class methods, that accepts or return year, month, date, hours, minutes,
and seconds values, the following conventions and representations are used:
 A year is represented by the integer y – 2000.
 A month is represented by an integer form 0 to 11; 0 is January, 1 is February,
2 is March, 3 is April, 4 is May, 5 is June, 6 is July, 7 is August, 8 is September,
9 is October, 10 is November and 11 is December.
 A day of month is represented in normal way, by an integer from 1 to 31.
 An hour is represented by an integer from 0 to 23. 12AM is hour 0.
 A minute is represented by an integer from 0 to 59 in the usual manner.
 A second is represented by an integer from 0 to 61. The values 60 and 61 are
used for leap calculations.

Methods of Date Class

Method Description
After(Date) Checks whether this date comes after the specified date.
Before(Date) Checks whether this date comes before the specified date.
getDate() Returns the day of the month.
getDay() Returns the day of the week.
getHours() Returns the hour.
getMinutes() Returns the minute.
getSeconds() Returns the second.
getMonth() Returns the month.
getTime() Returns the number of milliseconds since January 1, 1970,
00:00:00 GMT represented by this Date object.
getYear() Returns the year after 1900.

Page 13
setDate(int) Sets the date.
setDay(int) Sets the day of the week.
setHours(int) Sets the hours.
setMinutes(int) Sets the minutes.
setMonth(int) Sets the month.
setSeconds(int) Sets the seconds
setYear(int) Sets the year.
setTime(long) Sets the time.

Program to display current date and time


import java.util.Date;
import java.text.*;
public class DateExample
{
public static void main(String args[])
{
Date today=new Date();
System.out.println(today);
}
}
Output:
Fri Jan 17 10:19:19 IST 2014

Demonstration of Date methods


import java.util.Date;
import java.text.*;
public class DateExample
{
public static void main(String args[])
{
Date today=new Date();
System.out.println(today);

SimpleDateFormat df=new SimpleDateFormat("dd-MM-yy");


String date=df.format(today);

Page 14
System.out.println("Date="+today.getDate());
System.out.println("Day="+today.getDay());
System.out.println("Month="+today.getMonth());
System.out.println("Hours="+today.getHours());
System.out.println("Year="+today.getYear());
System.out.println("Time="+today.getTime());
today.setDate(20);
System.out.println("After changeing date="+today.getDate());
today.setYear(115);
System.out.println("After changeing Year="+today.getYear());
System.out.println(today);
}
}
Output:
Fri Jan 17 12:51:21 IST 2014
Date=17
Day=5
Month=0
Hours=12
Year=114
Time=1389943281732
After changeing date=20
After changeing Year=115
Tue Jan 20 12:51:21 IST 2015

Write a program to copy contents of one file to another file using character
stream class.
import java.io.*;
class copyf
{
public static void main(String args[]) throws IOException
{
BufferedReader in=null;

BufferedWriter out=null;
try
Page 15
{
in=new BufferedReader(new FileReader("input.txt"));
out=new BufferedWriter(new FileWriter("output.txt"));

int c;
while((c=in.read())!=-1)
{
out.write(c);
}
System.out.println("File copied successfully");
}
finally
{
if(in!=null)
{
in.close();
}
if(out!=null)
{
out.close();
}
}
}
}

Page 16

You might also like