CH-6. File Java_notes.
CH-6. File Java_notes.
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
Page 1
InputStream class hierarchy
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.
Page 2
OutputStream class hierarchy
Page 3
Hierarchy of reader stream classes
Methods in Reader Class:
Page 4
All the methods in Writer class returns a void value and throws an IOException.
The methods are:
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.
Page 6
read(charBuffer dest);
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.
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.
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. What is use of ArrayList Class ?State any three methods with their use
from ArrayList.
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).
Page 11
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
}
}
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
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.
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.
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