0% found this document useful (0 votes)
99 views69 pages

Unit 14 Input Output

The document discusses Java input/output (I/O) and file handling. It covers key I/O concepts like streams, input streams, output streams, and standard streams. It also covers the File class, which allows working with files and directories in Java. Methods of the File class are described that allow getting file properties, renaming, deleting, and other operations on files and directories.

Uploaded by

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

Unit 14 Input Output

The document discusses Java input/output (I/O) and file handling. It covers key I/O concepts like streams, input streams, output streams, and standard streams. It also covers the File class, which allows working with files and directories in Java. Methods of the File class are described that allow getting file properties, renaming, deleting, and other operations on files and directories.

Uploaded by

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

https://genuinenotes.

com
Unit-14 / Java Programming - I

Unit 14: Input/output


Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.
We can perform file handling in Java by Java I/O API (Application Programming Interface)
Stream
 A stream is a sequence of data. It's called a stream because it is like a stream of water that
continues to flow.
 A Stream is linked to a physical layer by java I/O system to make input and output
operation in java. In general, a stream means continuous flow of data. Streams are clean
way to deal with input/output without having every part of your code understand the
physical detail.

Output stream vs Input stream


OutputStream
 The Output stream is used for writing data to a destination.
 Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
InputStream
 The Input stream is used to read data from a source.
 Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.

1 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Standard Streams
All the programming languages provide support for standard I/O where the user's program can
take input from a keyboard and then produce an output on the computer screen. Java provides the
following three standard streams −
 Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented as System.in.
 Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented
as System.out.
 Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err.
In Java, these three streams are created for us automatically. All these streams are attached with
the console.

File
 Although most of the classes defined by java.io operate on streams, the File class does
not.
 It deals directly with files and the file system. That is, the File class does not specify how
information is retrieved from or stored in files; it describes the properties of a file itself.
 A File object is used to obtain or manipulate the information associated with a disk file,
such as the permissions, time, date, and directory path, and to navigate subdirectory
hierarchies
 Java File class represents the files and directory pathnames in an abstract manner. This
class is used for creation of files and directories, file searching, file deletion, etc. The File
object represents the actual file/directory on the disk
 Files are a primary source and destination for data within many programs.
 A directory in Java is treated simply as a File with one additional property—a list of
filenames that can be examined by the list( ) method.
 The following constructors can be used to create File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
Here, directoryPath is the path name of the file; filename is the name of the file or
subdirectory; dirObj is a File object that specifies a directory; and uriObj is a URI
object that describes a file.

2 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

 The following example creates three files: f1, f2, and f3. The first File object is
constructed with a directory path as the only argument. The second includes two
arguments—the path and the filename. The third includes the file path assigned to
f1 and a filename; f3 refers to the same file as f2.

File defines many methods that obtain the standard properties of a File object. For example,
getName( ) returns the name of the file; getParent( ) returns the name of the parent directory;
and exists( ) returns true if the file exists, false if it does not. The following example
demonstrates several of the File methods. It assumes that a directory called “JAVA-I” exists in
E drive and it contains a file called “MyFile.txt”

package filehandling;
import java.io.File;

public class FileDemo {


static void printThis(String s){
System.out.println(s);
}
public static void main(String[] args) {
File f1 = new File("E:/JAVA-I/MyFile.txt");
printThis("File Name: "+f1.getName());
printThis("Path: "+f1.getPath());
printThis("Parent: "+f1.getParent());
printThis("Abs Path: "+f1.getAbsolutePath());
printThis(f1.exists()?"exists":" does not exist");
printThis(f1.canWrite()? "is writeable":" is not writeable");
printThis(f1.canRead()? "is readable":" is not readable");
printThis("is " + (f1.isDirectory()? " ":" not " + " a
directory"));

3 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

printThis(f1.isFile()? "is normal file" : " might be named


pipe");
printThis(f1.isAbsolute()? "is absolute" : " is not absolute");
printThis("File last modified :"+f1.lastModified());
printThis("File size: "+f1.length()+ " Bytes");
}
}

 Most of the File methods are self-explanatory. isFile( ) and isAbsolute( ) are not.
 isFile( ) returns true if called on a file and false if called on a directory. Also,
isFile( ) returns false for some special files, such as device drivers and named
pipes, so this method can be used to make sure the file will behave as a file.
 The isAbsolute( ) method returns true if the file has an absolute path and false if
its path is relative.
File includes two useful utility methods of special interest.
 The first is renameTo( ), shown here:
boolean renameTo(File newName)

4 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Here, the filename specified by newName becomes the new name of the invoking
File object. It will return true upon success and false if the file cannot be renamed
(if you attempt to rename a file so that it uses an existing filename, for example).
 The second utility method is delete( ), which deletes the disk file represented by
the path of the invoking File object. It is shown here:
boolean delete( )
You can also use delete( ) to delete a directory if the directory is empty. delete( )
returns true if it deletes the file and false if the file cannot be removed.

Here are some other File methods that you will find helpful:
Sr.No. Method & Description
1 boolean canExecute()
This method tests whether the application can execute the file denoted by this abstract
pathname.
2 boolean canRead()
This method tests whether the application can read the file denoted by this abstract
pathname.
3 boolean canWrite()
This method tests whether the application can modify the file denoted by this abstract
pathname.
4 int compareTo(File pathname)
This method compares two abstract pathnames lexicographically.
5 boolean createNewFile()
This method atomically creates a new, empty file named by this abstract pathname if
and only if a file with this name does not yet exist.
6 static File createTempFile(String prefix, String suffix)
This method creates an empty file in the default temporary-file directory, using the
given prefix and suffix to generate its name.
7 static File createTempFile(String prefix, String suffix, File directory)
This method Creates a new empty file in the specified directory, using the given
prefix and suffix strings to generate its name.
8 boolean delete()
This method deletes the file or directory denoted by this abstract pathname.
9 void deleteOnExit()
This method requests that the file or directory denoted by this abstract pathname be
deleted when the virtual machine terminates.
10 boolean equals(Object obj)
This method tests this abstract pathname for equality with the given object.
11 boolean exists()

5 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This method tests whether the file or directory denoted by this abstract pathname
exists.
12 File getAbsoluteFile()
This method returns the absolute form of this abstract pathname.
13 String getAbsolutePath()
This method returns the absolute pathname string of this abstract pathname.
14 File getCanonicalFile()
This method returns the canonical form of this abstract pathname.
15 String getCanonicalPath()
This method returns the canonical pathname string of this abstract pathname.
16 long getFreeSpace()
This method returns the number of unallocated bytes in the partition named by this
abstract path name.
17 String getName()
This method returns the name of the file or directory denoted by this abstract
pathname.
18 String getParent()
This method returns the pathname string of this abstract pathname's parent, or null if
this pathname does not name a parent directory.
19 File getParentFile()
This method returns the abstract pathname of this abstract pathname's parent, or null
if this pathname does not name a parent directory.
20 String getPath()
This method converts this abstract pathname into a pathname string.
21 long getTotalSpace()
This method returns the size of the partition named by this abstract pathname.
22 long getUsableSpace()
This method returns the number of bytes available to this virtual machine on the
partition named by this abstract pathname.
23 int hashCode()
This method computes a hash code for this abstract pathname.
24 boolean isAbsolute()
This method tests whether this abstract pathname is absolute.
25 boolean isDirectory()
This method tests whether the file denoted by this abstract pathname is a directory.
26 boolean isFile()
This method tests whether the file denoted by this abstract pathname is a normal file.
27 boolean isHidden()
This method tests whether the file named by this abstract pathname is a hidden file.
28 long lastModified()
This method returns the time that the file denoted by this abstract pathname was last
modified.
29 long length()
This method returns the length of the file denoted by this abstract pathname.
30 String[] list()

6 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This method returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname.
31 String[] list(FilenameFilter filter)
This method returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname that satisfy the specified filter.
32 File[] listFiles()
This method returns an array of abstract pathnames denoting the files in the directory
denoted by this abstract pathname.
33 File[] listFiles(FileFilter filter)
This method returns an array of abstract pathnames denoting the files and directories
in the directory denoted by this abstract pathname that satisfy the specified filter.
34 File[] listFiles(FilenameFilter filter)
This method returns an array of abstract pathnames denoting the files and directories
in the directory denoted by this abstract pathname that satisfy the specified filter.
35 static File[] listRoots()
This method lists the available filesystem roots.
36 boolean mkdir()
This method creates the directory named by this abstract pathname.
37 boolean mkdirs()
This method creates the directory named by this abstract pathname, including any
necessary but non existent parent directories.
38 boolean renameTo(File dest)
This method renames the file denoted by this abstract pathname.
39 boolean setExecutable(boolean executable)
This is a convenience method to set the owner's execute permission for this abstract
pathname.
40 boolean setExecutable(boolean executable, boolean ownerOnly)
This method Sets the owner's or everybody's execute permission for this abstract
pathname.
41 boolean setLastModified(long time)
This method sets the last-modified time of the file or directory named by this abstract
pathname.
42 boolean setReadable(boolean readable)
This is a convenience method to set the owner's read permission for this abstract
pathname.
43 boolean setReadable(boolean readable, boolean ownerOnly)
This method sets the owner's or everybody's read permission for this abstract
pathname.
44 boolean setReadOnly()
This method marks the file or directory named by this abstract pathname so that only
read operations are allowed.
45 boolean setWritable(boolean writable)
This is a convenience method to set the owner's write permission for this abstract
pathname.
46 boolean setWritable(boolean writable, boolean ownerOnly)

7 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This method sets the owner's or everybody's write permission for this abstract
pathname.
47 String toString()
This method returns the pathname string of this abstract pathname.
48 URI toURI()
This method constructs a file : URI that represents this abstract pathname.

Directories
 A directory is a File that contains a list of other files and directories. When you create a
File object that is a directory, the isDirectory( ) method will return true. In this case, you
can call list( ) on that object to extract the list of other files and directories inside. It has
two forms. The first is shown here:
String[ ] list( )
The list of files is returned in an array of String objects. The program shown here
illustrates how to use list( ) to examine the contents of a directory:

Using FilenameFilter
You will often want to limit the number of files returned by the list( ) method to include only
those files that match a certain filename pattern, or filter. To do this, you must use a second form
of list( ), shown here:
String[ ] list(FilenameFilter FFObj)
In this form, FFObj is an object of a class that implements the FilenameFilter interface.
FilenameFilter defines only a single method, accept( ), which is called once for each file in a
list. Its general form is given here:
boolean accept(File directory, String filename)
The accept( ) method returns true for files in the directory specified by directory that should be
included in the list (that is, those that match the filename argument) and returns false for those
files that should be excluded.

The listFiles( ) Alternative


There is a variation to the list( ) method, called listFiles( ), which you might find useful. The
signatures for listFiles( ) are shown here:
File[ ] listFiles( )
File[ ] listFiles(FilenameFilter FFObj)
File[ ] listFiles(FileFilter FObj)

8 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

These methods return the file list as an array of File objects instead of strings. The first method
returns all files, and the second returns those files that satisfy the specified FilenameFilter.
Aside from returning an array of File objects, these two versions of listFiles( ) work like their
equivalent list( ) methods. The third version of listFiles( ) returns those files with path names
that satisfy the specified FileFilter. FileFilter defines only a single method, accept( ), which is
called once for each file in a list. Its general form is given here:
boolean accept(File path)
The accept( ) method returns true for files that should be included in the list (that is, those that
match the path argument) and false for those that should be excluded.

Creating Directories
Another two useful File utility methods are mkdir( ) and mkdirs( ).
 The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure can occur for various reasons, such as the path specified in the File object already
exists, or the directory cannot be created because the entire path does not exist yet. To
create a directory for which no path exists, use the mkdirs( ) method. It creates both a
directory and all the parents of the directory.
// Example
package filehandling;

import java.io.File;
import java.io.FilenameFilter;

public class DirDemo {


public static void main(String[] args) {
//Use the mkdir() method to create a single directory
File d1 = new File("F:/CoreJAVA");
if (d1.mkdir()) {
System.out.println("Directory created");
} else {
System.out.println("Directory not created");
}

9 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

//You can also use the mkdirs()method to create nested


//directories
File d2 = new
File("F:/Books/ComputerScience/Programming/Java");
if (d2.mkdirs()) {
System.out.println("Directories created");
} else {
System.out.println("Directories not created");
//Use the list() method on a Fileobject to list the content
//of a directory.
File d3 = new File("E:/JAVA-I");
String[] content = d3.list();
for (String s : content) {
System.out.println(s);
}
}
//You can supply a FilenameFilter to another overload of the
//list()
//method to list only files and directories that satisfy a
//condition.
File d5 = new File("E:/JAVA-I");
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File file, String name) {
return name.endsWith(".txt");
}
};
String[] cont = d5.list(filter);
for (String entry : cont) {
System.out.println(entry);
}

10 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

//Similarly, the methods listFiles() and


//listFiles(FilenameFilter) do the same, but return an
//array of File objects
File d6 = new File("E:/Deep Learning");
File allfiles[] = d6.listFiles();
for(File f:allfiles) {
System.out.println(f);
}
}
}

11 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

The AutoCloseable, Closeable, and Flushable Interfaces


 There are three interfaces that are quite important to the stream classes.
 Thy are AutoCloseable, Closeable, and Flushable
 Closeable and Flushable are defined in java.io and were added by JDK 5. The third,
AutoCloseable, was added by JDK 7. It is packaged in java.lang.

The AutoCloseable interface

o AutoCloseable provides support for the try-with-resources statement, which


automates the process of closing a resource. Only objects of classes that
implement AutoCloseable can be managed by try-with-resources.
o The AutoCloseable interface defines only the close( ) method:
void close( ) throws Exception
This method closes the invoking object, releasing any resources that it may hold.
It is called automatically at the end of a try-with-resources statement, thus
eliminating the need to explicitly call close( ). Because this interface is
implemented by all of the I/O classes that open a stream, all such streams can be
automatically closed by a try-with-resources statement.
o Automatically closing a stream ensures that it is properly closed when it is no
longer needed, thus preventing memory leaks and other problems.
The Closeable interface
 The Closeable interface also defines the close( ) method. Objects of a class that
implement Closeable can be closed. Beginning with JDK 7, Closeable extends
AutoCloseable. Therefore, any class that implements Closeable also implements
AutoCloseable.

Flushable Interface
 Objects of a class that implements Flushable can force buffered output to be written to
the stream to which the object is attached. It defines the flush( ) method, shown here:
void flush( ) throws IOException
 Flushing a stream typically causes buffered output to be physically written to the
underlying device. This interface is implemented by all of the I/O classes that write to a
stream.

12 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

I/O Exceptions
 Two exceptions play an important role in I/O handling.
o The first is IOException. As it relates to most of the I/O classes described in this
chapter, if an I/O error occurs, an IOException is thrown.
o In many cases, if a file cannot be opened, a FileNotFoundException is thrown.
FileNotFoundException is a subclass of IOException, so both can be caught
with a single catch that catches IOException. However, you might find it useful
to catch each exception separately.
 Another exception class that is sometimes important when performing I/O is
SecurityException. In situations in which a security manager is present, several of the
file classes will throw a SecurityException if a security violation occurs when
attempting to open a file. By default, applications run via java (dos command to run java
program) do not use a security manager.

Two Ways to Close a Stream


o In general, a stream must be closed when it is no longer needed. Failure to do so can
lead to memory leaks and resource starvation.
o Beginning with JDK 7, there are two basic ways in which you can close a stream.
 The first is to explicitly call close( ) on the stream. This is the traditional
approach that has been used since the original release of Java. With this
approach, close( ) is typically called within a finally block. Thus, a simplified
skeleton for the traditional approach is shown here:

 The second approach to closing a stream is to automate the process by using


the try-with resources statement that was added by JDK 7.
 The try-with-resources statement is an enhanced form of try that has the
following form:

Here, resource-specification is a statement or statements that declares and


initializes a resource, such as a file or other stream-related resource. It consists of
a variable declaration in which the variable is initialized with a reference to the
object being managed. When the try block ends, the resource is automatically
13 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

released. In the case of a file, this means that the file is automatically closed.
Thus, there is no need to call close( ) explicitly.
Here are three key points about the try-with-resources statement:
 Resources managed by try-with-resources must be objects of classes
that implement AutoCloseable.
 The resource declared in the try is implicitly final.
 You can manage more than one resource by separating each
declaration by a semicolon.
Also, remember that the scope of the declared resource is limited to the try-with-
resources statement. The principal advantage of try-with-resources is that the resource (in
this case, a stream) is closed automatically when the try block ends. Thus, it is not
possible to forget to close the stream, for example. The try-with-resources approach also
typically results in shorter, clearer, easier-to-maintain source code.

14 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

The Stream Classes


 Java’s stream-based I/O is built upon four abstract classes: InputStream,
OutputStream, Reader, and Writer.
 They are used to create several concrete stream subclasses.
 Although our programs perform their I/O operations through concrete subclasses, the
top-level classes define the basic functionality common to all stream classes.
 InputStream and OutputStream are designed for byte streams.
 Reader and Writer are designed for character streams.
 The byte stream classes and the character stream classes form separate hierarchies.
 In general, we should use the character stream classes when working with characters
or strings and we should use the byte stream classes when working with bytes or
other binary objects.

15 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

The 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.
 The byte stream classes are topped by InputStream and OutputStream.
InputStream (an abstract class)
 InputStream is an abstract class that defines Java’s model of streaming byte input. It
implements the AutoCloseable and Closeable interfaces. Most of the methods in this
class will throw an IOException when an I/O error occurs. (The exceptions are mark( )
and markSupported( ) methods .)
 List of methods is shown in following table

Sr.No. Method & Description


1 int available()
This method returns an estimate of the number of 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()
This method closes this input stream and releases any system resources associated
with the stream.
3 void mark(int readlimit)
This method marks the current position in this input stream.
4 boolean markSupported()
This method tests if this input stream supports the mark and reset methods.
5 abstract int read()
This method reads the next byte of data from the input stream.
6 int read(byte[] b)
This method reads some number of bytes from the input stream and stores them into
the buffer array b.
7 int read(byte[] b, int off, int len) <
This method reads up to len bytes of data from the input stream into an array of bytes.
8 void reset()
This method repositions this stream to the position at the time the mark method was
last called on this input stream.
9 long skip(long n)
This method skips over and discards n bytes of data from this input stream.

16 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

OutputStream ( an abstract class)


 OutputStream is an abstract class that defines streaming byte output. It implements the
AutoCloseable, Closeable, and Flushable interfaces. Most of the methods defined by
this class return void and throw an IOException in the case of I/O errors.
 List of methods is shown in following table

Sr.No. Method & Description


1 void close()
This method closes this output stream and releases any system resources associated
with this stream.
2 void flush()
This method flushes this output stream and forces any buffered output bytes to be
written out.
3 void write(byte[] b)
This method writes b.length bytes from the specified byte array to this output stream.
4 void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to this
output stream.
5 abstract void write(int b)
This method writes the specified byte to this output stream.

FileInputStream
 The FileInputStream class creates an InputStream that you can use to read bytes from
a file. Two commonly used constructors are shown here:
FileInputStream(String filePath)
FileInputStream(File fileObj)
Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file.

17 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Steps to follow to read data from file using FileInputStream


 Add import java.io.*; statement
 Handle FileNotFoundException and IOException
 Create FileInputStream class object ( let’s say, fis)
 Invoke fis.read(); method and assign it to int type variable
 Display or read the byte data return from the file
 Close stream after usage by using fis.close(); [We can also use try-with
resource where closing happens automatically]
Notes:

 fis.read() returns the given byte available in the file, if there is no byte
available, it returns -1
 Only one byte at a time can be read. To read multiple bytes (complete file) we
have to use while loop.
 The value is read in integer format so casting is needed.
 We can also use other overloaded versions of read() method. In such case, we
should proceed accordingly.

Example:
File: myFile.txt

File: FISExample.java

18 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

package filehandling;
import java.io.*;
public class FISExample {
public static void main(String args[]){
final String FILEPATH ="E:/JAVA-I/myFile.txt";
try{
FileInputStream fin=new FileInputStream(FILEPATH);
//this reads only a byte from the file
int v = fin.read();
//printing v by casting to char
System.out.println((char)v);
//to read multiple bytes
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){
System.out.println("Proble occured : "+e);
}
}
}

19 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful Methods of java.io.FileInputStream class

Sr.No. Method & Description

1 int available()

This method 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()
This method closes this file input stream and releases any system resources
associated with the stream.
3 protected void finalize()
This method ensures that the close method of this file input stream is called
when there are no more references to it.
4 FileChannel getChannel()
This method returns the unique FileChannel object associated with this file
input stream.

5 FileDescriptor getFD()
This method returns the FileDescriptor object that represents the connection
to the actual file in the file system being used by this FileInputStream.
6 int read()
This method reads a byte of data from this input stream.
7 int read(byte[] b)
This method reads up to b.length bytes of data from this input stream into an
array of bytes.
8 int read(byte[] b, int off, int len)
This method reads up to len bytes of data from this input stream into an array
of bytes.
9 long skip(long n)
This method skips over and discards n bytes of data from the input stream.

20 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

FileOutputStream
 FileOutputStream creates an OutputStream that you can use to write bytes to a file. It
implements the AutoCloseable, Closeable, and Flushable interfaces. Four of its
constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
They can throw a FileNotFoundException. Here, filePath is the full path name of a file,
and fileObj is a File object that describes the file. If append is true, the file is opened in
append mode.
 Creation of a FileOutputStream is not dependent on the file already existing.
FileOutputStream will create the file before opening it for output when you create the
object.
 In the case where you attempt to open a read-only file, an exception will be thrown.

Steps to follow to write data to a file using FileOutputStream


 Add import java.io.*; statement
 Handle FileNotFoundException and IOException
 Create FileOutputStream class object ( let’s say, fos)
 Invoke fos.write(data);
 Close stream after usage by using fos.close(); [We can also use try-with
resource where closing happens automatically]
Notes:

 fos.write()writes one byte at a time.


 We can also use other overloaded versions of write() method

21 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Example:
package filehandling;
import java.io.*;
public class FOSExample{
public static void main(String args[]) throws IOException{
FileOutputStream fout=new FileOutputStream("E:/abc.txt");
//these statements write single byte
fout.write(66);
fout.write('T');
fout.write(' ');
//to write string
String s="Who am I?";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}
}

22 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful methods of java.io.FileOutputStream class


Sr.No. Method & Description
1 void close()
This method closes this file output stream and releases any system resources
associated with this stream.
2 protected void finalize()
This method cleans up the connection to the file, and ensures that the close method of
this file output stream is called when there are no more references to this stream.
3 FileChannel getChannel()
This method returns the unique FileChannel object associated with this file output
stream.
4 FileDescriptor getFD()
This method returns the file descriptor associated with this stream.
5 void write(byte[] b)
This method writes b.length bytes from the specified byte array to this file output
stream.
6 void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to this
file output stream.
7 void write(int b)
This method writes the specified byte to this file output stream

23 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Write a program to read from a file and write to another file


Before executing the program

//Program to read from a file and write to another file


//File copying
package filehandling;
import java.io.*;

public class FileCopyingDemo {


public static void main(String[] args) {
//creating two File objects
File f1 = new File("E:/myFile1.txt");
File f2 = new File("E:/myFile2.txt");
try{
//creating FileInputStream object for reading
FileInputStream fis = new FileInputStream(f1);

24 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

//creating FileOutputStream object for writing


FileOutputStream fos = new FileOutputStream(f2);
int i=0;
//to read from one file and write to another
while((i=fis.read())!=-1){
char c = (char)i;
fos.write(c);
}
fis.close();
fos.close();
System.out.println("contents of one file is copied to
another file");
}catch(IOException ioe){
System.out.println("I/O Error: "+ioe);
}
}}

After executing the program

25 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

PrintStream
 The PrintStream class provides all of the output capabilities we have been using from
the System file handle, System.out, since beginning. This makes PrintStream one of
Java’s most often used classes.
 It implements the Appendable, AutoCloseable, Closeable, and Flushable interfaces.
 PrintStream defines several constructors. The ones shown next have been specified from
the start:

Here, outputStream specifies an open OutputStream that will receive output. The
autoFlushingOn parameter controls whether the output buffer is automatically flushed
every time a newline (\n) character or a byte array is written or when println( ) is called.
If autoFlushingOn is true, flushing automatically takes place. If it is false, flushing is not
automatic. The first constructor does not automatically flush. You can specify a character
encoding by passing its name in charSet.
 The next set of constructors gives you an easy way to construct a PrintStream that
writes its output to a file:

These allow a PrintStream to be created from a File object or by specifying the name of
a file. In either case, the file is automatically created. Any preexisting file by the same
name is destroyed. Once created, the PrintStream object directs all output to the
specified file. You can specify a character encoding by passing its name in charSet.
 PrintStream supports the print( ) and println( ) methods for all types, including Object.
If an argument is not a primitive type, the PrintStream methods will call the object’s
toString( ) method and then display the result.
 With the release of JDK 5, the printf( ) method was added to PrintStream. It allows you
to specify the precise format of the data to be written. The printf( ) method uses the
Formatter class to format data. It then writes this data to the invoking stream. Although
formatting can be done manually, by using Formatter directly, printf( ) streamlines the
process. It also parallels the C/C++ printf( ) function, which makes it easy to convert
existing C/C++ code into Java.

26 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

o The printf( ) method has the following general forms:


PrintStream printf(String fmtString, Object … args)
PrintStream printf(Locale loc, String fmtString, Object … args)
The first version writes args to standard output in the format specified by fmtString,
using the default locale. The second lets you specify a locale. Both return the invoking
PrintStream.
 In general, printf( ) works in a manner similar to the format( ) method specified by
Formatter. The fmtString consists of two types of items. The first type is composed of
characters that are simply copied to the output buffer. The second type contains format
specifiers that define the way the subsequent arguments, specified by args, are displayed.
 Because System.out is a PrintStream, you can call printf( ) on System.out. Thus,
printf( ) can be used in place of println( ) when writing to the console whenever
formatted output is desired. For example, the following program uses printf( ) to output
numeric values in various formats. Prior to JDK 5, such formatting required a bit of work.
With the addition of printf( ), this is now an easy task.
//Example of java PrintStream class

27 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

The content of a text file testout.txt is set with the below data

28 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful Methods of java.io.PrintStream Class


Sr.No. Method & Description
1 PrintStream append(char c)
This method appends the specified character to this output stream.
2 PrintStream append(CharSequence csq)
This method appends the specified character sequence to this output stream.
3 PrintStream append(CharSequence csq, int start, int end)
This method appends a subsequence of the specified character sequence to this output
stream.
4 boolean checkError()
This method flushes the stream and checks its error state.
5 protected void clearError()
This method clears the internal error state of this stream.
6 void close()
This method closes the stream.
7 void flush()
This method flushes the stream.
8 PrintStream format(Locale l, String format, Object... args)
This method writes a formatted string to this output stream using the specified format
string and arguments.
9 PrintStream format(String format, Object... args)
This method writes a formatted string to this output stream using the specified format
string and arguments.
10 void print(boolean b)
This method prints a boolean value.
11 void print(char c)
This method prints a character.
12 void print(char[] s)
This method prints an array of characters.
13 void print(double d)
This method prints a double-precision floating-point number.
14 void print(float f)
This method prints a floating-point number.
15 void print(int i)
This method prints an integer.
16 void print(long l)
This method prints a long integer.
17 void print(Object obj)
This method prints an object.
18 void print(String s)
This method Prints a string.
19 PrintStream printf(Locale l, String format, Object... args)

29 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This is a convenience method to write a formatted string to this output stream using
the specified format string and arguments.
20 PrintStream printf(String format, Object... args)
This is a convenience method to write a formatted string to this output stream using
the specified format string and arguments.
21 void println()
This method terminates the current line by writing the line separator string.
22 void println(boolean x)
This method prints a boolean and then terminate the line.
23 void println(char x)
This method prints a character and then terminate the line.
24 void println(char[] x)
This method prints an array of characters and then terminate the line.
25 void println(double x)
This method prints a double and then terminate the line.
26 void println(float x)
This method Prints a float and then terminate the line.
27 void println(int x)
This method prints an integer and then terminate the line.
28 void println(long x)
This method prints a long and then terminate the line.
29 void println(Object x)
This method prints an Object and then terminate the line.
30 void println(String x)
This method prints a String and then terminate the line.
31 protected void setError()
This method sets the error state of the stream to true.
32 void write(byte[] buf, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to this
stream.
33 void write(int b)
This method writes the specified byte to this stream.

30 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Output:

31 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

 PrintStream also defines the format( ) method. It has these general forms:
PrintStream format(String fmtString, Object … args)
PrintStream format(Locale loc, String fmtString, Object … args)
It works exactly like printf( ).

DataOutputStream and DataInputStream

 DataOutputStream and DataInputStream enable you to write or read primitive data to


or from a stream.
 They implement the DataOutput and DataInput interfaces, respectively. These
interfaces define methods that convert primitive values to or from a sequence of bytes.
 These streams make it easy to store binary data, such as integers or floating-point values,
in a file.
DataOutputStream
 DataOutputStream extends FilterOutputStream, which extends OutputStream. In
addition to implementing DataOutput, DataOutputStream also implements
AutoCloseable, Closeable, and Flushable.
 DataOutputStream defines the following constructor:
DataOutputStream(OutputStream outputStream)
Here, outputStream specifies the output stream to which data will be written.
 When a DataOutputStream is closed (by calling close( )), the underlying stream
specified by outputStream is also closed automatically.
 DataOutputStream supports all of the methods defined by its superclasses. However, it
is the methods defined by the DataOutput interface, which it implements, that make it
interesting. DataOutput defines methods that convert values of a primitive type into a
byte sequence and then writes it to the underlying stream. Here is a sampling of these
methods:
final void writeDouble(double value) throws IOException
final void writeBoolean(boolean value) throws IOException
final void writeInt(int value) throws IOException
Here, value is the value written to the stream.
Example of DataOutputStream class
In this example, we are writing the data to a text file testout.txt using DataOutputStream class.

32 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful Methods of java.io.DataOutputStream class

Sr.No. Method & Description


1 void flush()
This method flushes this data output stream.
2 int size()
This method returns the current value of the counter written, the number of bytes
written to this data output stream so far.
3 void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to the
underlying output stream.

33 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

4 void write(int b)
This method writes the specified byte (the low eight bits of the argument b) to the
underlying output stream.
5 void writeBoolean(boolean v)
This method writes a boolean to the underlying output stream as a 1-byte value.
6 void writeByte(int v)
This method writes out a byte to the underlying output stream as a 1-byte value.
7 void writeBytes(String s)
This method writes out the string to the underlying output stream as a sequence of
bytes.
8 void writeChar(int v)
This method writes a char to the underlying output stream as a 2-byte value, high
byte first.
9 void writeChars(String s)
This method writes a string to the underlying output stream as a sequence of
characters.
10 void writeDouble(double v)
This method converts the double argument to a long using the doubleToLongBits
method in class Double, and then writes that long value to the underlying output
stream as an 8-byte quantity, high byte first.
11 void writeFloat(float v)
This method converts the float argument to an int using the floatToIntBits method in
class Float, and then writes that int value to the underlying output stream as a 4-byte
quantity, high byte first.
12 void writeInt(int v)
This method writes an int to the underlying output stream as four bytes, high byte
first.
13 void writeLong(long v)
This method writes a long to the underlying output stream as eight bytes, high byte
first.
14 void writeShort(int v)
This method writes a short to the underlying output stream as two bytes, high byte
first.
15 void writeUTF(String str)
This method writes a string to the underlying output stream using modified UTF-8
encoding in a machine-independent manner.

34 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

DataInputStream
 DataInputStream is the complement of DataOuputStream. It extends
FilterInputStream, which extends InputStream. In addition to implementing the
DataInput interface, DataInputStream also implements AutoCloseable and Closeable.
 Here is its only constructor:
DataInputStream(InputStream inputStream)
Here, inputStream specifies the input stream from which data will be read.
 When a DataInputStream is closed (by calling close( )), the underlying stream specified
by inputStream is also closed automatically.
 Like DataOutputStream, DataInputStream supports all of the methods of its
superclasses, but it is the methods defined by the DataInput interface that make it
unique. These methods read a sequence of bytes and convert them into values of a
primitive type. Here is a sampling of these methods:
final double readDouble( ) throws IOException
final boolean readBoolean( ) throws IOException
final int readInt( ) throws IOException

Example of DataInputStream class


In this example, we are reading the data from the file myFile.txt file.

35 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

36 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful methods of java.io.DataInputStream

Sr.No. Method & Description


1 int read(byte[] b)
This method reads some number of bytes from the contained input stream and stores
them into the buffer array b
2 int read(byte[] b, int off, int len)
This method reads up to len bytes of data from the contained input stream into an
array of bytes.
3 boolean readBoolean()
This method reads one input byte and returns true if that byte is nonzero, false if that
byte is zero.
4 byte readByte()
This method reads and returns one input byte.
5 char readChar()
This method reads two input bytes and returns a char value.
6 double readDouble()
This method reads eight input bytes and returns a double value.
7 float readFloat()
This method reads four input bytes and returns a float value.
8 void readFully(byte[] b)
This method reads some bytes from an input stream and stores them into the buffer
array b.
9 void readFully(byte[] b, int off, int len)
This method reads len bytes from an input stream.
10 int readInt()
This method reads four input bytes and returns an int value.
11 long readLong()
This method reads eight input bytes and returns a long value.
12 short readShort()
This method reads two input bytes and returns a short value.
13 int readUnsignedByte()
This method reads one input byte, zero-extends it to type int, and returns the result,
which is therefore in the range 0 through 255.
14 int readUnsignedShort()
This method reads two input bytes and returns an int value in the range 0 through
65535.
15 String readUTF()
This method reads in a string that has been encoded using a modified UTF-8 format.
16 static String readUTF(DataInput in)
This method reads from the stream in a representation of a Unicode character string
encoded in modified UTF-8 format; this string of characters is then returned as a
String.

37 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

17 int skipBytes(int n)
This method makes an attempt to skip over n bytes of data from the input stream,
discarding the skipped bytes.

// To demonstrate DataInputStream and DataOutputStream


//This program uses try-with resources for exception handling
package filehandling;
import java.io.*;
public class DataIODemo {
public static void main(String[] args) {
final String FILEPATH= "E:/JAVA-I/abc.txt";
//First writing the data
try(DataOutputStream dout =
new DataOutputStream(new FileOutputStream(FILEPATH)))
{
dout.writeDouble(99.89);
dout.writeInt(200);
dout.writeBoolean(true);
}catch(FileNotFoundException fnoe ){
System.out.println("Cannot open the file");
}
catch(IOException ioe ){
System.out.println("I/O Error occured" +ioe);
}
//Now Reading the data from file
try(DataInputStream din =
new DataInputStream(new FileInputStream(FILEPATH)))
{
double d = din.readDouble();

38 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

int i = din.readInt();
boolean b = din.readBoolean();
System.out.println("Values are : ");
System.out.println("d= "+d +"\t i= "+i+"\t b= "+b);
}catch(FileNotFoundException fnoe ){
System.out.println("Cannot open the file");
}
catch(IOException ioe ){
System.out.println("I/O Error occured" +ioe);
}
}
}

RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations. If end-of-file is reached before the desired number of
byte has been read than EOFException is thrown. It is a type of IOException.
 RandomAccessFile encapsulates a random-access file. It is not derived from
InputStream or OutputStream. Instead, it implements the interfaces DataInput and
DataOutput, which define the basic I/O methods. It also implements the AutoCloseable
and Closeable interfaces.
 RandomAccessFile is special because it supports positioning requests—that is, you can
position the file pointer within the file.
 It has these two constructors:

39 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

In the first form, fileObj specifies the file to open as a File object. In the second form, the
name of the file is passed in filename. In both cases, access determines what type of file
access is permitted.
 If it is "r", then the file can be read, but not written.
 If it is "rw", then the file is opened in read-write mode.
 If it is "rws", the file is opened for read-write operations and every
change to the file’s data or metadata will be immediately written to the
physical device.
 If it is "rwd", the file is opened for read-write operations and every
change to the file’s data will be immediately written to the physical
device.
 The method seek( ), shown here, is used to set the current position of the file pointer
within the file:
void seek(long newPos) throws IOException
Here, newPos specifies the new position, in bytes, of the file pointer from the beginning
of the file. After a call to seek( ), the next read or write operation will occur at the new
file position.
 RandomAccessFile implements the standard input and output methods, which you can
use to read and write to random access files. It also includes some additional methods.
One is setLength( ). It has this signature:
void setLength(long len) throws IOException
This method sets the length of the invoking file to that specified by len. This method can
be used to lengthen or shorten a file. If the file is lengthened, the added portion is
undefined.

Example:
Content of myTextFile.txt before executing the program

40 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

package filehandling;
import java.io.*;

public class RandomAccessFileExample {


static final String FILEPATH ="E:/JAVA-I/myTextFile.txt";
//creating method that can read randomly
private static byte[] readFromFile(RandomAccessFile f, long position, int size)
throws IOException{
f.seek(position);
byte[] bytes = new byte[size];
f.read(bytes);
return bytes;
}
//creating method that can write randomly
private static void writeToFile(RandomAccessFile f, String data, long position)
throws IOException {
f.seek(position);
f.write(data.getBytes());
}

public static void main(String[] args) {

String reading=null;

41 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

String writing ="Love all";


try {
long fp=0;
//creating random access file object in read write mode
RandomAccessFile file = new RandomAccessFile(FILEPATH, "rw");
fp= file.getFilePointer();
System.out.println("Current position of file pointer = "+ fp);
file.seek(6);
fp= file.getFilePointer();
System.out.println("After seek(6), position of file pointer = "+ fp);
System.out.println("Lets read file from this position");
//this reads 20 bytes from current position
byte a[] = readFromFile(file,fp,20);
reading = new String(a);
System.out.println(reading);
fp= file.getFilePointer();
System.out.println("Now position of file pointer = "+ fp);
System.out.println("Lets write in the file");
writeToFile(file, writing,fp);
fp= file.getFilePointer();
System.out.println("Now position of file pointer = "+ fp);
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

42 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Content of myTextFile.txt after executing the program

43 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful methods of java.io.RandomAccessFile class

Sr.No. Method & Description


1 void close()
This method Closes this random access file stream and releases any system resources
associated with the stream.
2 FileChannel getChannel()
This method returns the unique FileChannel object associated with this file.
3 FileDescriptor getFD()
This method returns the opaque file descriptor object associated with this stream.
4 long getFilePointer()
This method returns the current offset in this file.
5 long length()
This method returns the length of this file.
6 int read()
This method reads a byte of data from this file.
7 int read(byte[] b)
This method reads up to b.length bytes of data from this file into an array of bytes.
8 int read(byte[] b, int off, int len)
This method reads up to len bytes of data from this file into an array of bytes.
9 boolean readBoolean()
This method reads a boolean from this file.
10 byte readByte()
This method reads a signed eight-bit value from this file.
11 char readChar()
This method reads a character from this file.
12 double readDouble()
This method reads a double from this file.
13 float readFloat()
This method reads a float from this file.
14 void readFully(byte[] b)
This method reads b.length bytes from this file into the byte array, starting at the
current file pointer.
15 void readFully(byte[] b, int off, int len)
This method reads exactly len bytes from this file into the byte array, starting at the
current file pointer.
16 int readInt()
This method reads a signed 32-bit integer from this file.
17 String readLine()
This method reads the next line of text from this file.
18 long readLong()
This method reads a signed 64-bit integer from this file.
19 short readShort()
This method reads a signed 16-bit number from this file.
20 int readUnsignedByte()

44 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This method reads an unsigned eight-bit number from this file.


21 int readUnsignedShort()
This method reads an unsigned 16-bit number from this file.
22 String readUTF()
This method reads in a string from this file.
23 void seek(long pos)
This method sets the file-pointer offset, measured from the beginning of this file, at
which the next read or write occurs.
24 void setLength(long newLength)
This method sets the length of this file.
25 int skipBytes(int n)
This method attempts to skip over n bytes of input discarding the skipped bytes.
26 void write(byte[] b)
This method writes b.length bytes from the specified byte array to this file, starting at
the current file pointer.
27 void write(byte[] b, int off, int len)
This method writes len bytes from the specified byte array starting at offset off to this
file.
28 void write(int b)
This method writes the specified byte to this file.
29 void writeBoolean(boolean v)
This method writes a boolean to the file as a one-byte value.
30 void writeByte(int v)
This method writes a byte to the file as a one-byte value.
31 void writeBytes(String s)
This method writes the string to the file as a sequence of bytes.
32 void writeChar(int v)
This method writes a char to the file as a two-byte value, high byte first.
33 void writeChars(String s)
This method writes a string to the file as a sequence of characters.
34 void writeDouble(double v)
This method converts the double argument to a long using the doubleToLongBits
method in class Double, and then writes that long value to the file as an eight-byte
quantity, high byte first.
35 void writeFloat(float v)
This method converts the float argument to an int using the floatToIntBits method in
class Float, and then writes that int value to the file as a four-byte quantity, high byte
first.
36 void writeInt(int v)
This method writes an int to the file as four bytes, high byte first.
37 void writeLong(long v)
This method writes a long to the file as eight bytes, high byte first.
38 void writeShort(int v)
This method writes a short to the file as two bytes, high byte first.
39 void writeUTF(String str)

45 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This method writes a string to the file using modified UTF-8 encoding in a machine-
independent manner.

The Character Streams


 While the byte stream classes provide sufficient functionality to handle any type of I/O
operation, they cannot work directly with Unicode characters. Since one of the main
purposes of Java is to support the "write once, run anywhere" philosophy, it was
necessary to include direct I/O support for characters.
 At the top of the character stream hierarchy there are the Reader and Writer abstract
classes.
Reader
 Reader is an abstract class that defines Java’s model of streaming character input. It
implements the AutoCloseable, Closeable, and Readable interfaces.
 All of the methods in this class (except for markSupported( )) will throw an
IOException on error conditions. Writer
Useful methods of java.io.Reader Class
Sr.No. Method & Description
1 abstract void close()
This method closes the stream and releases any system
resources associated with it.
2 void mark(int readAheadLimit)
This method marks the present position in the stream.
3 boolean markSupported()
This method tells whether this stream supports the
mark() operation.
4 int read()
This method reads a single character.
5 int read(char[] cbuf)
This method reads characters into an array.
6 abstract int read(char[] cbuf, int off, int len)
This method reads characters into a portion of an
array.
7 int read(CharBuffer target)
This method attempts to read characters into the
specified character buffer.
8 boolean ready()
This method tells whether this stream is ready to be
read.
9 void reset()
This method resets the stream.
10 long skip(long n)
This method skips characters.

46 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Writer
 Writer is an abstract class that defines streaming character output. It implements the
AutoCloseable, Closeable, Flushable, and Appendable interfaces.
 All of the methods in this class throw an IOException in the case of errors.
Useful methods of java.io.Reader Class

Sr.No. Method & Description


1 Writer append(char c)
This method appends the specified character to this
writer.
2 Writer append(CharSequence csq)
This method appends the specified character sequence to
this writer.
3 Writer append(CharSequence csq, int start, int end)
This method appends a subsequence of the specified
character sequence to this writer.
4 abstract void close()
This method loses the stream, flushing it first.
5 abstract void flush()
This method flushes the stream.
6 void write(char[] cbuf)
This method writes an array of characters.
7 abstract void write(char[] cbuf, int off, int len)
This method writes a portion of an array of characters.
8 void write(int c)
This method writes a single character.
9 void write(String str)
This method writes a string.
10 void write(String str, int off, int len)
This method writes a portion of a string.

FileReader
 The FileReader class creates a Reader that you can use to read the contents of a file.
 Two commonly used constructors are shown here:
FileReader(String filePath)
FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file.

47 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful methods of java.io.FileReader class


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

 The following example shows how to read lines from a file and display them on the
standard output device
//to demonstrate FileReader
//try-with resource is used for exception handling
package filehandling;
import java.io.*;
public class FRExample {
public static void main(String args[]){
try(FileReader fr=new FileReader("E:/abc.txt")){
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
System.out.println("\n File reading completed ");
}catch(IOException ioe){
System.out.println("I/O Error : "+ ioe);
}
}
}

FileWriter
 FileWriter creates a Writer that you can use to write to a file. Four commonly used
constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can all throw an IOException. Here, filePath is the full path name of a file, and
fileObj is a File object that describes the file. If append is true, then output is appended
to the end of the file.

48 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

 Creation of a FileWriter is not dependent on the file already existing. FileWriter will
create the file before opening it for output when you create the object. In the case where
you attempt to open a read-only file, an IOException will be thrown.

Useful methods of java.io.FileWriter class


Methods 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 flush the data of FileWriter.
void close() It is used to close the FileWriter.

//to demonstrate FileWriter


package filehandling;
import java.io.*;
public class FWExample {
public static void main(String args[]) throws Exception {
FileWriter fw=new FileWriter("E:/abc.txt");
fw.write("Do good.Be good.");
fw.close();
System.out.println("writing completed!");
}
}

49 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

PrintWriter
 PrintWriter is essentially a character-oriented version of PrintStream. It implements
the Appendable, AutoCloseable, Closeable, and Flushable interfaces.
 PrintWriter has several constructors. The following have been supplied by PrintWriter
from the start:
PrintWriter(OutputStream outputStream)
PrintWriter(OutputStream outputStream, boolean autoFlushingOn)
PrintWriter(Writer outputStream)
PrintWriter(Writer outputStream, boolean autoFlushingOn)
Here, outputStream specifies an open OutputStream that will receive output. The
autoFlushingOn parameter controls whether the output buffer is automatically flushed every
time println( ), printf( ), or format( ) is called. If autoFlushingOn is true, flushing
automatically takes place. If false, flushing is not automatic. Constructors that do not specify
the autoFlushingOn parameter do not automatically flush.
 The next set of constructors gives you an easy way to construct a PrintWriter that writes
its output to a file.

These allow a PrintWriter to be created from a File object or by specifying the name of
a file. In either case, the file is automatically created. Any preexisting file by the same
name is destroyed. Once created, the PrintWriter object directs all output to the
specified file. You can specify a character encoding by passing its name in charSet.
 PrintWriter supports the print( ) and println( ) methods for all types, including Object.
If an argument is not a primitive type, the PrintWriter methods will call the object’s
toString( ) method and then output the result.
 PrintWriter also supports the printf( ) method. It works the same way it does in the
PrintStream class described earlier: It allows you to specify the precise format of the
data. Here is how printf( ) is declared in PrintWriter:
PrintWriter printf(String fmtString, Object … args)
PrintWriter printf(Locale loc, String fmtString, Object …args)

50 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

The first version writes args to standard output in the format specified by fmtString, using
the default locale. The second lets you specify a locale. Both return the invoking
PrintWriter.
 The format( ) method is also supported. It has these general forms:
PrintWriter format(String fmtString, Object … args)
PrintWriter format(Locale loc, String fmtString, Object … args)
It works exactly like printf( ).

//To demonstrate PrintWriter


package filehandling;
import java.io.*;
public class PrintWriterExample {
public static void main(String[] args) throws Exception {
//to write on Console using PrintWriter
PrintWriter writer = new PrintWriter(System.out);
writer.write("I have nothing to say...\n");
writer.flush();
writer.close();
//to write in File using PrintWriter
PrintWriter writer1;
writer1 = new PrintWriter(new File("E:/abc.txt"));
writer1.write("Hearing and listening are not same");
writer1.flush();
writer1.close();
}
}

51 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Useful methods of java.io.PrintWriter class


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

Byte Streams vs Character Streams


Byte Streams
 Java Byte streams are used to perform input and output of 8-bit bytes. Though
there are many classes related to byte streams but the most frequently used classes
are, FileInputStream and FileOutputStream
Character Streams
 Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode.
Though there are many classes related to character streams but the most frequently
used classes are, FileReader and FileWriter. Though internally FileReader uses
FileInputStream and FileWriter uses FileOutputStream but here the major
difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.

52 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Write a program to read the text from keyboard and write to a file.
//To read from keyboard and write to a file
package filehandling;
import java.io.*;
import java.util.Scanner;
public class FromKeyBoardToFile {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String inputData = "";
System.out.println("Write whatever you like..type'exit' at last");
File myfile = new File("E:/xyz.txt");
try(FileWriter fw = new FileWriter(myfile)) {
while(true){
//read line by line
inputData= sc.nextLine();
//if "Exit" is typed,come out from the loop
if(inputData.equalsIgnoreCase("exit"))
break;
//write the line
fw.write(inputData);
//write newline character
fw.write("\r\n");
}
System.out.println("Thank you ! Your data has been saved to 'E:/xyz.txt'");
} catch(IOException ioe){
System.out.println("I/O proble: "+ ioe);
}

53 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

}
}

54 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

55 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

The Console Class


 The Console class was added to java.io by JDK 6. It is used to read from and write to the
console, if one exists.
 It implements the Flushable interface. Console is primarily a convenience class because
most of its functionality is available through System.in and System.out. However, its use
can simplify some types of console interactions, especially when reading strings from the
console.
 Console supplies no constructors. Instead, a Console object is obtained by calling
System.console( ), which is shown here:
static Console console( )
If a console is available, then a reference to it is returned. Otherwise, null is returned. A
console will not be available in all cases. Thus, if null is returned, no console I/O is
possible.
 Console defines the methods shown in table below. Notice that the input methods, such
as readLine( ), throw IOError if an input error occurs. IOError is a subclass of Error.
It indicates an I/O failure that is beyond the control of your program. Thus, you will not
normally catch an IOError. Frankly, if an IOError is thrown while accessing the
console, it usually means there has been a catastrophic system failure. Also notice the
readPassword( ) methods. These methods let your application read a password without
echoing what is typed. When reading passwords, you should "zero-out" both the array
that holds the string entered by the user and the array that holds the password that the
string is tested against. This reduces the chance that a malicious program will be able to
obtain a password by scanning memory.

Useful methods of java.io.Console class


Methods Description
Reader reader() It is used to retrieve the
reader object associated with
the console
String readLine() It is used to read a single
line of text from the console.
String readLine(String fmt, It provides a formatted prompt
Object... args) then reads the single line of
text from the console.
char[] readPassword() It is used to read password
that is not being displayed on
the console.
char[] readPassword(String fmt, It provides a formatted prompt
Object... args) then reads the password that

56 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

is not being displayed on the


console.
Console format(String fmt, It is used to write a
Object... args) formatted string to the
console output stream.
Console printf(String format, It is used to write a string
Object... args) to the console output stream.
PrintWriter writer() It is used to retrieve
the PrintWriter object
associated with the console.
void flush() It is used to flushes the
console.

//Program to demonstrate Console class

import java.io.Console;
public class ConsoleTest{
public static void main(String args[]){
//obtain a reference to the console
Console c=System.console();
//if no console available, exit
if(c==null) return;
//to read a string
System.out.println("Enter UserName: ");
String u = c.readLine();
//to read password
System.out.println("Enter password: ");
char [] p=c.readPassword();
String pass = new String(p);
//to display
System.out.println("UserName is: "+u);
System.out.println("Password is: "+pass);
} }

57 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Serialization

 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.
 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.
Serializable
 Only an object that implements the Serializable interface can be saved and restored by
the serialization facilities. The Serializable interface defines no members. It is simply

58 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

used to indicate that a class may be serialized. If a class is serializable, all of its
subclasses are also serializable.
 Variables that are declared as transient are not saved by the serialization facilities. Also,
static variables are not saved.
Externalizable
 The Java facilities for serialization and deserialization have been designed so that much
of the work to save and restore the state of an object occurs automatically. However,
there are cases in which the programmer may need to have control over these processes.
For example, it may be desirable to use compression or encryption techniques. The
Externalizable interface is designed for these situations.
 The Externalizable interface defines these two methods:

In these methods, inStream is the byte stream from which the object is to be read, and
outStream is the byte stream to which the object is to be written.
ObjectOutput
The ObjectOutput interface extends the DataOutput and AutoCloseable interfaces and
supports object serialization. It defines different methods. It defines the methods shown in table
below. Note especially the writeObject( ) method. This is called to serialize an object. All of
these methods will throw an IOException on error conditions.

59 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

ObjectOutputStream
 The ObjectOutputStream class extends the OutputStream class and implements the
ObjectOutput interface. It is responsible for writing objects to a stream. One constructor
of this class is shown here:
ObjectOutputStream(OutputStream outStream) throws IOException
The argument outStream is the output stream to which serialized objects will be written.
 Closing an ObjectOutputStream automatically closes the underlying stream specified
by outStream.
Useful methods of java.io.ObjectOutputStream
Sr.No. Method & Description
1 protected void annotateClass(Class <?> cl)
Subclasses may implement this method to allow class
data to be stored in the stream.
2 protected void annotateProxyClass(Class<?> cl)
Subclasses may implement this method to store custom
data in the stream along with descriptors for dynamic
proxy classes.
3 void close()
This method closes the stream.
4 void defaultWriteObject()
This method writes the non-static and non-transient
fields of the current class to this stream.
5 protected void drain()
This method drain any buffered data in
ObjectOutputStream.
6 protected boolean enableReplaceObject(boolean enable)
This method enable the stream to do replacement of
objects in the stream.
7 void flush()
This method flushes the stream.
8 ObjectOutputStream.PutField putFields()
This method retrieves the object used to buffer
persistent fields to be written to the stream.
9 protected Object replaceObject(Object obj)
This method will allow trusted subclasses of
ObjectOutputStream to substitute one object for another
during serialization.
10 void reset()
This method reset will disregard the state of any
objects already written to the stream.
60 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

11 void useProtocolVersion(int version)


This method specify stream protocol version to use when
writing the stream.
12 void write(byte[] buf)
This method writes an array of bytes.
13 void write(byte[] buf, int off, int len)
This method writes a sub array of bytes.
14 void write(int val)
This method writes a byte.
15 void writeBoolean(boolean val)
This method writes a boolean.
16 void writeByte(int val)
This method writes an 8 bit byte.
17 void writeBytes(String str)
This method writes a String as a sequence of bytes.
18 void writeChar(int val)
This method writes a 16 bit char.
19 void writeChars(String str)
This method writes a String as a sequence of chars.
20 protected void writeClassDescriptor(ObjectStreamClass
desc)
This method writes the specified class descriptor to
the ObjectOutputStream.
21 void writeDouble(double val)
This method writes a 64 bit double.
22 void writeFields()
This method writes the buffered fields to the stream.
23 void writeFloat(float val)
This method writes a 32 bit float.
24 void writeInt(int val)
This method writes a 32 bit int.
25 void writeLong(long val)
This method writes a 64 bit long.
26 void writeObject(Object obj)
This method writes the specified object to the
ObjectOutputStream.
27 protected void writeObjectOverride(Object obj)
This method is used by subclasses to override the
default writeObject method.
28 void writeShort(int val)
This method writes a 16 bit short.
29 protected void writeStreamHeader()
This method is provided so subclasses can append or
prepend their own header to the stream.
30 void writeUnshared(Object obj)

61 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This method writes an "unshared" object to the


ObjectOutputStream.

ObjectInput
 The ObjectInput interface extends the DataInput and AutoCloseable interfaces and
defines the methods shown in table below.
 It supports object serialization. Note especially the readObject( ) method. This is called
to deserialize an object. All of these methods will throw an IOException on error
conditions. The readObject( ) method can also throw ClassNotFoundException.

ObjectInputStream
 The ObjectInputStream class extends the InputStream class and implements the
ObjectInput interface. ObjectInputStream is responsible for reading objects from a
stream.
 One constructor of this class is shown here:
ObjectInputStream(InputStream inStream) throws IOException
The argument inStream is the input stream from which serialized objects should be read.
 Closing an ObjectInputStream automatically closes the underlying stream specified by
inStream.

62 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

 Several commonly used methods in this class are shown in following table. They will
throw an IOException on error conditions. The readObject( ) method can also throw
ClassNotFoundException.

Useful methods of java.io.ObjectInputStream


Sr.No. Method & Description
1 int available()
This method returns the number of bytes that can be
read without blocking.
2 void close()
This method closes the input stream.
3 void defaultReadObject()
This method reads the non-static and non-transient
fields of the current class from this stream.
4 protected boolean enableResolveObject(boolean enable)
This method enables the stream to allow objects read
from the stream to be replaced.
5 int read()
This method reads a byte of data.
6 int read(byte[] buf, int off, int len)
This method reads into an array of bytes.
7 boolean readBoolean()
This method reads in a boolean.
8 byte readByte()
This method reads an 8 bit byte.
9 char readChar()
This method r a 16 bit char.
10 protected ObjectStreamClass readClassDescriptor()
This method read a class descriptor from the
serialization stream.
11 double readDouble()
This method reads a 64 bit double.
12 ObjectInputStream.GetField readFields()
This method reads the persistent fields from the stream
and makes them available by name.
13 float readFloat()
This method reads a 32 bit float.
14 void readFully(byte[] buf)
This method reads bytes, blocking until all bytes are
read.
15 void readFully(byte[] buf, int off, int len)
This method reads bytes, blocking until all bytes are
read.
16 int readInt()

63 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This method reads a 32 bit int.


17 long readLong()
This method reads a 64 bit long.
18 Object readObject()
This method reads an object from the ObjectInputStream.
19 protected Object readObjectOverride()
This method is called by trusted subclasses of
ObjectOutputStream that constructed ObjectOutputStream
using the protected no-arg constructor.
20 short readShort()
This method reads a 16 bit short.
21 protected void readStreamHeader()
This method is provided to allow subclasses to read and
verify their own stream headers.
22 Object readUnshared()
This method reads an "unshared" object from the
ObjectInputStream.
23 int readUnsignedByte()
This method reads an unsigned 8 bit byte.
24 int readUnsignedShort()
This method reads an unsigned 16 bit short.
25 String readUTF()
This method reads a String in modified UTF-8 format.
26 void registerValidation(ObjectInputValidation obj, int
prio)
This method register an object to be validated before
the graph is returned.
27 protected Class<?> resolveClass(ObjectStreamClass desc)
This method loads the local class equivalent of the
specified stream class description.
28 protected Object resolveObject(Object obj)
This method will allow trusted subclasses of
ObjectInputStream to substitute one object for another
during deserialization.
29 protected Class<?> resolveProxyClass(String[]
interfaces)
This method returns a proxy class that implements the
interfaces named in a proxy class descriptor;
subclasses may implement this method to read custom
data from the stream along with the descriptors for
dynamic proxy classes, allowing them to use an
alternate loading mechanism for the interfaces and the
proxy class.
30 int skipBytes(int len)
This method skips bytes.

64 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

Java ‘transient’ Keyword

Java transient keyword is used in serialization. If you define any data member as transient, it
will not be serialized.

import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
transient int age;//Now it will not be serialized
public Student(int id, String name,int age) {
this.id = id;
this.name = name;
this.age=age;
}
}

65 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

A Serialization Example
The following program illustrates how to use object serialization and deserialization. It begins by
instantiating an object of class MyClass. This object has three instance variables that are of types
String, int, and double. This is the information we want to save and restore.
A FileOutputStream is created that refers to a file named "serial", and an
ObjectOutputStream is created for that file stream. The writeObject( ) method of
ObjectOutputStream is then used to serialize our object. The object output stream is flushed
and closed.
A FileInputStream is then created that refers to the file named "serial", and an
ObjectInputStream is created for that file stream. The readObject( ) method of
ObjectInputStream is then used to deserialize our object. The object input stream is then
closed.
Note that MyClass is defined to implement the Serializable interface. If this is not done, a
NotSerializableException is thrown. Try experimenting with this program by declaring some of
the MyClass instance variables to be transient. That data is then not saved during serialization.

66 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

67 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

This program demonstrates that the instance variables of object1 and object2 are identical. The
output is shown here:

Another example to demonstrate serialization and deserialization process

package filehandling;
import java.io.*;
class Demo implements Serializable{
int i =10;
double d = 55.77;
String s = "Hello";
}
public class SerDeserDemo {
public static void main(String[] args) throws Exception {
Demo obj = new Demo();
//serialization
FileOutputStream fos = new FileOutputStream("E:/pqr.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
System.out.println("Serializaion Completed");
//deserialization
FileInputStream fis = new FileInputStream("E:/pqr.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Demo obj1= (Demo) ois.readObject();
System.out.println("Deserialization completed ");

68 Collected by Bipin Timalsina

https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I

System.out.println("Values in the object");


System.out.println("i = "+ obj1.i+" d= "+ obj1.d+ " s= "+obj1.s);
}

69 Collected by Bipin Timalsina

https://genuinenotes.com

You might also like