Professional Documents
Culture Documents
inforAfter 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
The ObjectOutputStream class contains many write methods for writing various data
types such as writeObject() method. This method serializes an Object and sends it to
the output stream. Similarly, the ObjectInputStream class contains method for
deserializing an object as readObject(). 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
All of the fields in the class must be serializable. If a field is not serializable, it must
be marked transient.
2) What is use of stream classes? Write any two methods FileReader class.
Streams support many different kinds of data, including simple bytes, primitive
Some streams simply pass on data; others manipulate and transform the data in
useful ways. Java‟s stream based I/O is built upon four abstract classes:
They are used to create several concrete stream subclasses, the top level classes
InputStream and OutputStream are designed for byte streams and used to work
Reader and Writer are designed for character streams and used to work with
character or string.
2. public int read(char[] cbuf, int offset, int length) throws IOException - Reads characters into
a portion of an array.
3. public void close()throws IOException - Closes the stream and releases any system resources
associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or
skip() invocations will throw an IOException. Closing a previously closed stream has no
effect
4. public boolean ready()throws IOException - Tells whether this stream is ready to be read. An
inputStreamReader is ready if its input buffer is not empty, or if bytes are available to be read
5. public void mark(int readAheadLimit) throws IOException -Marks the present position in the
stream. Subsequent calls to reset() will attempt to reposition the stream to this point. Not all
then attempt to reposition it at the mark. If the stream has not been marked, then attempt to
reset it in some way appropriate to the particular stream, for example by repositioning it to its starting
point. Not all character-input streams support the reset() operation, and some support reset() without
supporting mark().
3) Write any two methods of file and file input stream class each.
Returns the name of the file or directory denoted by this abstract pathname.
Tests whether the application can read the file denoted by this abstract
pathname. Returns true if and only if the file specified by this abstract
Tests whether the application can modify to the file denoted by this
abstract pathname. Returns true if and only if the file system actually
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
Returns true if and only if the file denoted by this abstract pathname exists
Tests whether the file denoted by this abstract pathname is a normal file. A
guaranteed to be a normal file. Returns true if and only if the file denoted
Returns the time that the file denoted by this abstract pathname was last
modified. Returns a long value representing the time the file was last
January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.
Returns the length of the file denoted by this abstract pathname. The return
value is unspecified if this pathname denotes a directory.
can be read (or skipped over) from this input stream without blocking by
2) void close() Closes this file input stream and releases any system resources
4) int read(byte[] b) Reads up to b.length bytes of data from this input stream
5) read(byte[] b, int off, int len) Reads up to len bytes of data from this input
import java.io.*;
class filetest
int rollno=0;
File f1;
File f2;
FileReader in=null;
FileWriter out=null;
void getdata(String s)
String ch="y";
try
f1=new File(s);
while(ch.compareTo("y")==0)
System.out.println("Enter name");
n=b.readLine();
System.out.println("Enter number:");
rollno=Integer.parseInt(b.readLine());
out.write(Integer.toString(rollno));
out.write(" ");
out.write(n);
ch=b.readLine();
if (ch.compareTo("y")==0)
out.write('\n');
out.write('\n');
out.close();
void wordcount(String s)
int r=0,count=0,c=0;
try
while(r!=-1)
r=in.read();
if(r=='\n')
c++;
count++;
System.out.println("No. of words:"+count);
System.out.println("No. of lines:"+c);
in.close();
catch(IOException e){System.out.println(e);}
void display(String s)
int r =0;
try
in = new FileReader(f1);
while(r!=-1)
r=in.read();
System.out.print((char)r);
in.close();
void filecopy(String s)
int r =0;
try
f2=new File("output.txt");
in = new FileReader(f1);
while(r!=-1)
r=in.read();
out.write((char)r);
}
in.close();
out.close();
catch(IOException e){System.out.println(e);}
f.getdata(filename);
f.filecopy(filename);
f.display(filename);
f.wordcount(filename);
5] What are stream classes? List any two input stream classes from character stream.
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
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. 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
Reader stream classes:--it is used to read characters from files. These classes are
functionally similar to the input stream classes, except input streams use bytes as their
1. BufferedReader
2. CharArrayReader
3. InputStreamReader
4. FileReader
5. PushbackReader
6. FilterReader
7. PipeReader
8. StringReader
6] What are streams? Write any two methods of character stream classes.
Ans:
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information (i.e it takes the input or gives the output). A stream is
linked to a physical device by the Java I/O system. All streams behave in the same
manner, even if the actual physical devices to which they are linked differ. Thus, the
same I/O classes and methods can be applied to any type of device.Java 2 defines two types of streams:
byte and character. Byte streams provide a
convenient means for handling input and output of bytes. Byte streams are used, for
example, when reading or writing binary data. Character streams provide a convenient
means for handling input and output of characters. They use Unicode and, therefore, can
be internationalized. Also, in some cases, character streams are more efficient than byte
streams.
Character streams are defined by using two class hierarchies. At the top are two abstract
classes, Reader and Writer. These abstract classes handle Unicode character streams.
1) void mark(int numChars) : Places a mark at the current point in the input stream
stream.
3) int read( ) :Returns an integer representation of the next available character from the
invoking input stream. –1 is returned when the end of the file is encountered.
buffer and returns the actual number of characters that were successfully read. –1 is
characters successfully read.–1 is returned when the end of the file is encountered.
6) boolean ready( ): Returns true if the next input request will not wait. Otherwise, it
returns false.
7) void reset( ): Resets the input pointer to the previously set mark.
8) long skip(long numChars) :- Skips over numChars characters of input, returning the
9) abstract void close( ) :- Closes the input source. Further read attempts will generate
Writer is an abstract class that defines streaming character output. All of the methods
in this class return a void value and throw an IOException in the case of error
1) abstract void close( ) : Closes the output stream. Further write attempts will generate
an IOException.
2) abstract void flush( ) : Finalizes the output state so that any buffers are cleared. That
3) void write(intch): Writes a single character to the invoking output stream. Note that
the parameter is an int, which allows you to call write with expressions without having to
4) void write(char buffer[ ]): Writes a complete array of characters to the invoking
output stream
5) abstract void write(char buffer[ ],int offset, int numChars) :- Writes a subrange of
numChars characters from the array buffer, beginning at buffer[offset] to the invoking
output stream.
7) void write(String str, int offset,int numChars): Writes a sub range of numChars
4. void deleteOnExit( ) -Removes the file associated with the invoking object when the
5. boolean isHidden( )-Returns true if the invoking file is hidden. Returns false
otherwise.
1. int available( )- Returns the number of bytes of input currently available for reading.
2. void close( )- Closes the input source. Further read attempts will generate an
IOException.
3. void mark(int numBytes) -Places a mark at the current point in the inputstream that
invoking stream.
5. int read( )- Returns an integer representation of the next available byte of input. –1 is
6. int read(byte buffer[ ])- Attempts to read up to buffer.length bytes into buffer and
returns the actual number of bytes that were successfully read. –1 is returned when
Ans:
byte stream.
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
The ObjectOutputStream class contains many write methods for writing various data
types such as writeObject() method. This method serializes an Object and sends it to
the output stream. Similarly, the ObjectInputStream class contains method for
deserializing an object as readObject(). 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
All of the fields in the class must be serializable. If a field is not serializable, it must
be marked transient
9]What are stream classes? List any two input stream classes from character stream.
Ans:
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. 1. Byte stream classes that provide support for handling I/O operations
on bytes. 2. 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 Reader stream
classes:-it is used to read characters from files. These classes are functionally
similar to the input stream classes, except input streams use bytes as their fundamental unit of
information while reader streams use characters
1. BufferedReader
2. CharArrayReader
3. InputStreamReader
4. FileReader
5. PushbackReader
6. FilterReader
7. PipeReader
8. StringReader
Ans:
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,
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
Example:
Assume that an object to be serialized has references to other objects, which, inturn, 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
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.
FileOutputStream(File file)
This creates a file output stream to write to the file represented by the
FileOutputStream(String name)
This creates an output file stream to write to the file with the
specified name.
Example:
import java.io.*;
class FileoutputstreamExample
FileInputStreamfis = null;
FileOutputStreamfos = null;
try {
intch;
while((ch=fis.read())!=-1)
fos.write(ch);
} catch(Exception e)
finally{
if(fis != null)
fis.close();
if(fos != null)
fos.close();
}
}
12) Write a program to copy contents of one file to another file using
import java.io.*;
class FileCopyExample {
int c=0;
while(c!=-1)
c=fr.read();
fw.write(c);
fr.close();
fw.close();
System.out.println("file copied");
}
13]Explain serialization with suitable example for writing an object into file. 6 M 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
RMI allows a Java object on one machine to invoke a method of a Java object
remote method. The sending machine serializes the object and transmits it. The
Example:
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
scenarios. If you attempt to serialize an object at the top of an object graph, all
Similarly, during the process of deserialization, all of these objects and their
import java.io.*;
class Filecopy
int c=0;
try
while(c!=-1)
c=in.read();
out.write(c);
finally
if(in!=null)
in.close();
if(out!=null)
out.close();
}
}
Stream:
Java defines two types of streams: based on the datatype on which they operate
input and output of bytes. Byte streams are used, for example, when
Ans: 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. But, for reading streams
Method Description
int read() It is used to read the byte of data from the input
stream.
input stream.
int read(byte[] b, int
stream.
FileChannel
getChannel()
FileDescriptor
protected void
finalize()
import java.io.*;
while(dr.available() !=0)
System.out.println(dr.readLine());
}
dr.close();
18]Write any two methods of file and file input stream class each.
boolean canExecute() : Tests whether the application can execute the file
boolean canRead() : Tests whether the application can read the file denoted
boolean canWrite() : Tests whether the application can modify the file
lexicographically.
pathname.
boolean equals(Object obj) : Tests this abstract pathname for equality with
boolean exists() : Tests whether the file or directory denoted by this abstract
pathname exists.
abstract pathname.
long getFreeSpace() : Returns the number of unallocated bytes in the
partition String getName() : Returns the name of the file or directory denoted by this
abstract pathname.
parent.
pathname’s parent.
directory.
boolean isFile() : Tests whether the file denoted by this abstract pathname is
a normal file.
boolean isHidden() : Tests whether the file named by this abstract pathname
is a hidden file.
long length() : Returns the length of the file denoted by this abstract
pathname.
String[] list() : Returns an array of strings naming the files and directories in
the directory .
the directory.
pathname.
boolean setReadOnly() : Marks the file or directory named so that only read
URI toURI() : Constructs a file URI that represents this abstract pathname.
int available(): It is used to return the estimated number of bytes that can be
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 off, int len): It is used to read up to len bytes of data
long skip(long x) :It is used to skip over and discards x bytes of data from
protected void finalize() : It is used to ensure that the close method is call when there is no more
reference to the file input stream.
class fileCopy
{
public static void main(String args[]) throws IOException
int c=0;
try
while(c!=-1)
c=in.read();
out.write(c);
finally
if(in!=null)
in.close();
if(out!=null)
out.close();
pathname.
Tests whether the application can read the file denoted by this
abstract pathname.
Tests whether the application can modify the file denoted by this
abstract pathname.
pathname exists.
directory.
normal file.
Returns the time that the file denoted by this abstract pathname
pathname if and only if a file with this name does not yet exist
Creates the directory named by this abstract pathname public boolean renameTo(File dest)
abstract pathname.
pathname.
Tests this abstract pathname for equality with the given object
public String toString()
import java.io.*;
class CountChars
try
while((ch=fr.read())!=-1)
fr.close();
System.out.println(c);
catch(Exception e) {}
import java.io.*;
class filecopy
{
FileInputStream in= new FileInputStream("input.txt"); //FileReader
int c=0;
try
while(c!=-1)
c=in.read();
out.write(c);
finally
if(in!=null)
in.close();
if(out!=null)
out.close();