Unit 14 Input Output
Unit 14 Input Output
com
Unit-14 / Java Programming - I
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.
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;
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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)
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()
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()
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)
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.
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;
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
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.
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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
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);
}
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
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.
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...");
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
Output:
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( ).
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
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
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
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:
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
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
package filehandling;
import java.io.*;
String reading=null;
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
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
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
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.
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)
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( ).
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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);
}
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
}
}
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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);
} }
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
Serialization
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.
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
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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.
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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;
}
}
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.
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
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:
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 ");
https://genuinenotes.com
https://genuinenotes.com
Unit-14 / Java Programming - I
https://genuinenotes.com