You are on page 1of 32

6]MANAGING INPUT/OUTPUT/FILE IN JAVA

1) Explain serialization in relation with stream class.

Serialization in java is a mechanism of writing the state of an object into a byte

stream.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

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

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 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

its appropriate data type.

For a class to be serialized successfully, two conditions must be met:

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.

2) What is use of stream classes? Write any two methods FileReader class.

An I/O Stream represents an input source or an output destination.


A stream can represent many different kinds of sources and destinations,

including disk files, devices, other programs, and memory arrays.

Streams support many different kinds of data, including simple bytes, primitive

data types, localized characters, and objects.

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:

InputStream, OutputStream, Reader, Writer.

They are used to create several concrete stream subclasses, the top level classes

define the basic functionality common to all stream classes.

InputStream and OutputStream are designed for byte streams and used to work

with bytes or other binary objects.

Reader and Writer are designed for character streams and used to work with

character or string.

1. public int read()throws IOException - Reads a single character.

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

from the underlying byte stream

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

character-input streams support the mark() operation.


6. public void reset()throws IOException - Resets the stream. If the stream has been marked,

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.

File class Methods:

1. public String getName()

Returns the name of the file or directory denoted by this abstract pathname.

2. public String getParent()

Returns the pathname string of this abstract pathname's parent, or null if

this pathname does not name a parent directory.

3. public File getParentFile()

Returns the abstract pathname of this abstract pathname's parent, or null if

this pathname does not name a parent directory.

4. public String getPath()

Converts this abstract pathname into a pathname string.

5. public boolean isAbsolute()

Tests whether this abstract pathname is absolute. Returns true if this

abstract pathname is absolute, false otherwise

6. public String getAbsolutePath()

Returns the absolute pathname string of this abstract pathname.

7. public boolean canRead()

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

pathname exists and can be read by the application; false otherwise.


8. public boolean canWrite()

Tests whether the application can modify to the file denoted by this

abstract pathname. Returns true if and only if the file system actually

contains a file denoted by this abstract pathname and the application is

allowed to write to the file; false otherwise.

9. 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

10. public boolean isDirectory()

Tests whether the file denoted by this abstract pathname is a directory.

Returns true if and only if the file denoted by this abstract pathname exists

and is a directory; false otherwise.

11. 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.

12. public long lastModified()

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

modified, measured in milliseconds since the epoch (00:00:00 GMT,

January 1, 1970), or 0L if the file does not exist or if an I/O error occurs.

13. public long length()

Returns the length of the file denoted by this abstract pathname. The return
value is unspecified if this pathname denotes a directory.

FileInputStream class methods :

(Any 2 methods can be considered) (2 M)

1) 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.

2) void close() Closes this file input stream and releases any system resources

associated with the stream.

3) int read() Reads a byte of data from this input stream.

4) int read(byte[] b) Reads up to b.length bytes of data from this input stream

into an array of bytes.

5) read(byte[] b, int off, int len) Reads up to len bytes of data from this input

stream into an array of bytes.

4) Write a program to copy contents of one file to another file using

character stream class.

import java.io.*;

class filetest

String n=" ";

int rollno=0;

File f1;

File f2;

FileReader in=null;

FileWriter out=null;

BufferedReader b=new BufferedReader(new


InputStreamReader(System.in));

void getdata(String s)

String ch="y";

try

f1=new File(s);

out= new FileWriter(f1);

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

System.out.println("More records :");

ch=b.readLine();

if (ch.compareTo("y")==0)

out.write('\n');

out.write('\n');

out.close();

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


}

void wordcount(String s)

int r=0,count=0,c=0;

try

f1= new File(s);

in= new FileReader(f1);

while(r!=-1)

r=in.read();

if(r=='\n')

c++;

if (r==' ' || r=='\n')

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

f1= new File(s);

in = new FileReader(f1);

while(r!=-1)

r=in.read();

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

in.close();

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

void filecopy(String s)

int r =0;

try

f1= new File(s);

f2=new File("output.txt");

in = new FileReader(f1);

out= new FileWriter(f2);

while(r!=-1)

r=in.read();

out.write((char)r);
}

System.out.println("File copied to output.txt...");

in.close();

out.close();

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

public static void main(String[] args)

filetest f= new filetest();

String filename= args[0];

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

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

Input Stream Classes

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.

The Character Stream Classes

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.

Java has several concrete subclasses of each of these.

Methods of Reader Class

1) void mark(int numChars) : Places a mark at the current point in the input stream

that will remain valid until numChars characters are read.

2) boolean markSupported( ) : Returns true if mark( ) / reset( ) are supported on this

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.

4) int read(char buffer[ ]) : Attempts to read up to buffer. Length characters into

buffer and returns the actual number of characters that were successfully read. –1 is

returned when the end of the file is encountered.

5) abstract int read(char buffer[ ],int offset,int numChars): Attempts to read up to

numChars characters into buffer starting at buffer[offset], returning the number of

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

number of characters actually skipped.

9) abstract void close( ) :- Closes the input source. Further read attempts will generate

an IOException[**Note: any two methods from above list to be considered]


Writer Class

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

Methods of Writer class are listed below: -

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

is, it flushes the output buffers.

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

cast them back to char.

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.

6) void write(String str): Writes str to the invoking output stream.

7) void write(String str, int offset,int numChars): Writes a sub range of numChars

characters from the array str, beginning at the specified offset.

[**Note: any two methods from above list to be considered]

7] Write any two methods of File and FileInputStream class each.

File Class Methods

1. String getName( ) - returns the name of the file.

2. String getParent( ) - returns the name of the parent directory.


3. boolean exists( ) - returns true if the file exists, false if it does not.

4. void deleteOnExit( ) -Removes the file associated with the invoking object when the

Java Virtual Machine terminates.

5. boolean isHidden( )-Returns true if the invoking file is hidden. Returns false

otherwise.

FileInputStream Class Methods:

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

will remain valid until numBytes bytes are read.

4. boolean markSupported( ) -Returns true if mark( )/reset( ) are supported by the

invoking stream.

5. int read( )- Returns an integer representation of the next available byte of input. –1 is

returned when the end of the file is encountered.

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

the end of the file is encountered

8) Explain Serialization in relation with stream classes.

Ans:

Serialization in java is a mechanism of writing the state of an object into a

byte stream.

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 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

its appropriate data type.

For a class to be serialized successfully, two conditions must be met:

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

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

Input Stream Classes

1. BufferedReader

2. CharArrayReader

3. InputStreamReader

4. FileReader

5. PushbackReader

6. FilterReader

7. PipeReader

8. StringReader

10]Explain serialization with stream classes.

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,

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:

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

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.

11}Describe file output stream class with one example.

A file output stream is an output stream for writing data to a File.

FileOutputStream class is used to write bytes of data into a file.

Constructor: (Any one)

FileOutputStream(File file)

This creates a file output stream to write to the file represented by the

specified File object.

FileOutputStream(String name)

This creates an output file stream to write to the file with the

specified name.

Example:

import java.io.*;

class FileoutputstreamExample

public static void main(String a[]) throws IOException


{

File fin = new File("in.txt");

File fout = new File("out.txt");

FileInputStreamfis = null;

FileOutputStreamfos = null;

try {

fis =new FileInputStream(fin);

fos = new FileOutputStream(fout);

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

character stream classes.

import java.io.*;

class FileCopyExample {

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

FileReaderfr = new FileReader("input.txt");

FileWriterfw = new FileWriter("output.txt");

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

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:

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.

14]Write a program to copy the contents of one file into another. 4 M

import java.io.*;
class Filecopy

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

FileInputStream in= new FileInputStream("input.txt"); //FileReader

class can be used

FileOutputStream out= new FileOutputStream("output.txt");

//FileWriter class can be used

int c=0;

try

while(c!=-1)

c=in.read();

out.write(c);

System.out.println("File copied to output.txt....");

finally

if(in!=null)

in.close();

if(out!=null)

out.close();

}
}

15]Explain stream and various types of streams. 4 M

Stream:

1. A stream in java is path along which data flows.

2. A stream is an abstraction that either produces or consumes information

(i.e. it takes the input or gives the output).

3. A stream presents a uniform, easy-to-use, object oriented interface

between program and input/output device.

4. It has source and destination.

Java defines two types of streams: based on the datatype on which they operate

1. Byte Stream: 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.

2. Character stream: 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.

16]Differentiate between Input stream class and Reader class.


17]Explain fileinputstream class to read the content of a file.

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

of characters, it is recommended to use File Reader class.

Java FileInputStream class methods

Method Description

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

off, int len)

It is used to read up to len bytes of data from the input

stream.

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

from the input stream.

FileChannel

getChannel()

It is used to return the unique FileChannel object

associated with the file input stream.

FileDescriptor

getFD() It is used to return the FileDescriptor object.

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.

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

Program for Reading contents from file:

import java.io.*;

public class f_demo

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

File f=new File(“c:/input.txt”);

DataInputStream dr=new DataInputStream(new FileInputStream(f));

while(dr.available() !=0)

System.out.println(dr.readLine());
}

dr.close();

18]Write any two methods of file and file input stream class each.

Ans: File class methods:

boolean canExecute() : Tests whether the application can execute the file

denoted by this abstract pathname.

boolean canRead() : Tests whether the application can read the file denoted

by this abstract pathname.

boolean canWrite() : Tests whether the application can modify the file

denoted by this abstract pathname.

int compareTo(File pathname) : Compares two abstract pathnames

lexicographically.

boolean createNewFile() : Atomically creates a new, empty file named by

this abstract pathname .

static File createTempFile(String prefix, String suffix) : Creates an empty

file in the default temporary-file directory.

boolean delete() : Deletes the file or directory denoted by this abstract

pathname.

boolean equals(Object obj) : Tests this abstract pathname for equality with

the given object.

boolean exists() : Tests whether the file or directory denoted by this abstract

pathname exists.

String getAbsolutePath() : Returns the absolute pathname string of this

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.

String getParent() : Returns the pathname string of this abstract pathname’s

parent.

File getParentFile() : Returns the abstract pathname of this abstract

pathname’s parent.

String getPath() : Converts this abstract pathname into a pathname string.

boolean isDirectory() : Tests whether the file denoted by this pathname is a

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 .

File[] listFiles() : Returns an array of abstract pathnames denoting the files in

the directory.

boolean mkdir() : Creates the directory named by this abstract pathname.

boolean renameTo(File dest) : Renames the file denoted by this abstract

pathname.

boolean setExecutable(boolean executable) : A convenience method to set

the owner’s execute permission.

boolean setReadable(boolean readable) : A convenience method to set the

owner’s read permission.

boolean setReadable(boolean readable, boolean ownerOnly) : Sets the


owner’s or everybody’s read permission.

boolean setReadOnly() : Marks the file or directory named so that only read

operations are allowed.

boolean setWritable(boolean writable) : A convenience method to set the

owner’s write permission.

String toString() : Returns the pathname string of this abstract pathname.

URI toURI() : Constructs a file URI that represents this abstract pathname.

FileInputStream class 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 off, int len): It is used to read up to len bytes of data

from the inpu stream.

long skip(long x) :It is used to skip over and discards x bytes of data from

the input stream.

FileChannel getChannel() : It is used to return the unique FileChannel

object associated with the file input stream.

FileDescriptor getFD() : It is used to return the FileDescriptor object.

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.

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

19]Write a program to copy contents of one file to another. Using

byte stream classes.

class fileCopy

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

FileInputStream in= new FileInputStream("input.txt");

FileOutputStream out= new FileOutputStream("output.txt");

int c=0;

try

while(c!=-1)

c=in.read();

out.write(c);

System.out.println("File copied to output.txt....");

finally

if(in!=null)

in.close();

if(out!=null)

out.close();

20]Write any four methods of file class with their use.

public String getName()


Returns the name of the file or directory denoted by this abstract

pathname.

public String getParent()

Returns the pathname string of this abstract 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 isAbsolute()

Tests whether this abstract pathname is absolute.

public String getAbsolutePath()

Returns the absolute pathname string of this abstract pathname.

public boolean canRead()

Tests whether the application can read the file denoted by this

abstract pathname.

public boolean canWrite()

Tests whether the application can modify the file denoted by this

abstract pathname.

public boolean exists()

Tests whether the file or directory denoted by this abstract

pathname exists.

public boolean isDirectory()

Tests whether the file denoted by this abstract pathname is a

directory.

public boolean isFile()

Tests whether the file denoted by this abstract pathname is a

normal file.

public boolean isHidden()

Tests whether the file named by this abstract pathname is a hidden


file

public long lastModified()

Returns the time that the file denoted by this abstract pathname

was last modified.

public long length()

Returns the length of the file denoted by this abstract pathname

public boolean createNewFile() throws IOException

Atomically creates a new, empty file named by this abstract

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

public boolean delete()

Deletes the file or directory denoted by this abstract pathname

public String[] list()

Returns an array of strings naming the files and directories in the

directory denoted by this abstract pathname.

public boolean mkdir()

Creates the directory named by this abstract pathname public boolean renameTo(File dest)

Renames the file denoted by this abstract pathname.

public boolean setLastModified(long time)

Sets the last-modified time of the file or directory named by this

abstract pathname.

public boolean setReadOnly()

Marks the file or directory named by this abstract pathname so

that only read operations are allowed

public boolean setWritable(boolean writable, boolean ownerOnly)

Sets the owner's or everybody's write permission for this abstract

pathname.

public boolean equals(Object obj)

Tests this abstract pathname for equality with the given object
public String toString()

Returns the pathname string of this abstract pathname

21]Write a program that will count no. of characters in a file.

import java.io.*;

class CountChars

public static void main(String args[])

try

FileReader fr=new FileReader("a.txt");

int ch; int c=0;

while((ch=fr.read())!=-1)

c++; //increase character count

fr.close();

System.out.println(c);

catch(Exception e) {}

22]Draw the hierarchy of Writer stream classes, and hierarchy of

Reader stream classes.


23]Write a java program to copy contents of one file to another file.

import java.io.*;

class filecopy

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

{
FileInputStream in= new FileInputStream("input.txt"); //FileReader

class can be used

FileOutputStream out= new FileOutputStream("output.txt");

//FileWriter class can be used

int c=0;

try

while(c!=-1)

c=in.read();

out.write(c);

System.out.println("File copied to output.txt....");

finally

if(in!=null)

in.close();

if(out!=null)

out.close();

You might also like