[go: up one dir, main page]

0% found this document useful (0 votes)
78 views31 pages

File Handling

This document discusses file handling and input/output streams in Java. It defines files, text files, binary files, and streams. It describes the File class for manipulating file information and the InputStream, OutputStream, FileInputStream, and FileOutputStream classes for reading from and writing to files. Filtered streams are also introduced as wrappers that provide additional functionality like buffering and character translation.

Uploaded by

Nootan Padia
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)
78 views31 pages

File Handling

This document discusses file handling and input/output streams in Java. It defines files, text files, binary files, and streams. It describes the File class for manipulating file information and the InputStream, OutputStream, FileInputStream, and FileOutputStream classes for reading from and writing to files. Filtered streams are also introduced as wrappers that provide additional functionality like buffering and character translation.

Uploaded by

Nootan Padia
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/ 31

11/16/2018

File Handling
By : Prof. Nootan Padia

Files
• A file is a collection of data in mass storage.
• A data file is not a part of a program’s source code.
• The same file can be read or modified by different programs.
• The program must be aware of the format of the data in the file.

By : Prof. Nootan Padia 1


11/16/2018

• The files are maintained by the operating system.


• The system provides commands and/or GUI utilities for viewing file
directories and for copying, moving, renaming, and deleting files.
• The operating system also provides basic functions, callable from
programs, for reading and writing directories and files.

Text Files
• A computer user distinguishes text (“ASCII”) files and “binary” files.
This distinction is based on how you treat the file.
• A text file is assumed to contain lines of text (for example, in ASCII
code).
• Each line terminates with a newline character (or a combination,
carriage return plus line feed).

By : Prof. Nootan Padia 2


11/16/2018

• Examples:
• Any plain-text file, typically named something.txt
• Source code of programs in any language (for example, Something.java)
• HTML documents
• Data files for certain programs, (for example, fish.dat; any file is a data file for
some program.)

Binary Files
• A “binary” file can contain any information, any combination of bytes.
• Only a programmer / designer knows how to interpret it.
• Different programs may interpret the same file differently (for
example, one program displays an image, another extracts an
encrypted message).

By : Prof. Nootan Padia 3


11/16/2018

• Examples:
• Compiled programs (for example, Something.class)
• Image files (for example, something.gif)
• Music files (for example, something.mp3)

Streams
• A stream is an abstraction derived from sequential input or output
devices.
• An object from which we can read a sequence of bytes is called an
input stream.
• An object to which we can write a sequence of bytes is called an
output stream.
• A file can be treated as an input or output stream.

By : Prof. Nootan Padia 4


11/16/2018

Random-Access Files
• A program can start reading or writing a random-access file at any
place and read or write any number of bytes at a time.
• “Random-access file” is an abstraction: any file can be treated as a
random-access file.
• You can open a random-access file both for reading and writing at the
same time.

• A binary file containing fixed-length data records is suitable for


random-access treatment.
• A random-access file may be accompanied by an “index” (either in
the same or a different file), which tells the address of each record.
• Tape : CD == Stream : Random-access

By : Prof. Nootan Padia 5


11/16/2018

File class
It is used to obtain and manipulate the information associated with a disk file,
such as permission, time , date etc.
Constructors :-
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URL urlObj)
Methods :-
void deleteOnExit() boolean isDirectory()
boolean isHidden() boolean isFile()
String getName() String getPath()
String getParent() int length()
String lastModified() boolean renameTo(File newfilename)
boolean exists() boolean delete()
boolean canRead()

The Byte Stream


• Byte stream is used for handling byte-oriented I/O.
• It can be used with any type of object, including binary data.
• It has two super classes :
• InputStream
• OutputStream

By : Prof. Nootan Padia 6


11/16/2018

InputStream class
• It is an abstract class that defines java’s model of streaming byte
input.
• All of the methods of this class will throw an IOException
• Methods :-
1) int available() – returns the no. of bytes which r readily
available for reading.
2) void close()
3) void mark(int readLimit) – marks the current position in
the source. A marked position will be lost if there are more than the
readlimit bytes read after a call to the mark() method.

4) boolean markSupported()
5) int read() – it returns -1 when there is an end of file
condition.
6) int read(byte buffer[])
7) int read(byte buffer[], int offset , int numBytes)
8) void reset() – takes to the last marked position.
9) long skip(long numBytes) – it indicates the no. of bytes to
be skipped. The method returns the no. of bytes which were skipped
or a -1 to indicate that an end of file was encountered.

By : Prof. Nootan Padia 7


11/16/2018

OuputStream class
• It is an abstract class that defines streaming byte output.
• All of the methods return void and throw IOException.
• Methods :-
void close()
void flush()
void write(int b)
void write(byte buffer[])
void write(byte buffer[] , int offset, int numBytes)

FileInputStream class
• This class creates an InputStream that you can use to read bytes from
a file.
• Constructors :-
FileInputStream(String filePath)
FileInputStream(File fileObj)

By : Prof. Nootan Padia 8


11/16/2018

FileOutputStream class
• This class creates an OutputStream that you can use to write bytes to
a file.
• Constructors :-
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean
append)
FileOutputStream(File fileObj, boolean
append)

Filtered streams
• Filtered streams are simply wrappers around underlying input or
output streams that transparently provide some extended level of
functionality.
• Typical extensions are buffering, character translation, and raw data
translation.
• Constructors :-
• FilterOutputStream(OutputStream os)
• FilterInputStream(InputStream is)
• FilterReader(Reader r)
• FilterWriter(Writer w)

By : Prof. Nootan Padia 9


11/16/2018

DataInputStream
• A data input stream lets an application read primitive Java data types
from an underlying input stream in a machine-independent way.
• An application uses a data output stream to write data that can later
be read by a data input stream.
• Constructor
DataInputStream(InputStream in)
Creates a DataInputStream that uses the specified underlying
InputStream.

• int read(byte[] b)
• intread(byte[] b, int off, int len)
• booleanreadBoolean()
• bytereadByte()
• charreadChar()
• doublereadDouble()
• floatreadFloat()

By : Prof. Nootan Padia 10


11/16/2018

• intreadInt()
• String readLine()
• longreadLong()
• shortreadShort()
• StringreadUTF()

DataOutputStream
• A data output stream lets an application write primitive Java data
types to an output stream .
• Constructor
DataOutputStream(OutputStream in)
Creates a DataOutputStream that uses the specified underlying
OutputStream.

By : Prof. Nootan Padia 11


11/16/2018

• writeBoolean(false);
• writeByte(Bytevalue);
• writeChar(charvalue);
• writeDouble(Doublevalue);
• writeFloat(Floatvalue);
• writeInt(Integervalue);
• writeLong(Longvalue);
• writeShort(Shortvalue);

Buffered Byte Streams


• For the byte-oriented streams, a buffered stream extends a filtered stream class
by attaching a memory buffer to the I/O streams.
• This buffer allows Java to do I/O operations on more than a byte at a time, hence
increasing performance.
• An optimal buffer size is generally dependent on the host operating system, the
amount of memory available, and how the machine is configured.
• There are two buffered byte streams :-
• BufferedInputStream
• BufferedOutputStream

By : Prof. Nootan Padia 12


11/16/2018

Buffered Byte streams


• BufferedInputStream :-
• It allows you to “wrap” any InputStream into a buffered stream and achieve the performance
improvement.
• Constructors :-
BufferedInputStream(InputStream is)
BufferedInputStream(InputStream is,int bufsize)
• BufferedOutputStream :-
• It is similar to OutputStream but it added flush() method that is used to ensure that data
buffers are physically written to the actual output device. Default size is 512 bytes.
• Constructors :-
BufferedOutputStream(OutputStream os)
BufferedOutputStream(OutputStream os, int bufSize)

PrintStream class
• This class provides all of the formatting capabilities we have been
using from the System file handle.
• Use print() and println() methods just like using with System class
object.
• Constructors :-
PrintStream(OutputStream os)
PrintStream(OutputStream os, boolean
flushOnNewLine)

By : Prof. Nootan Padia 13


11/16/2018

Random Access File


• It encapsulates a random access file.
• It is not derived from InputStream or OutputStrem. Instead, it implements the interfaces
DataInput and DataOutput.
• It also supports positioning requests – that is, you can position the file pointer within the file.
• Constructors :-
RandomAccessFile(String filename,String access) throws
FileNotFoundException
RandomAccessFile(File fileObj,String access)
throws FileNotFoundException
• Methods :-
void seek(long newPos) throws IOException
void setLength(long len) throws IOException

Character Streams
• Character stream is used for handling character-oriented I/O.
• It can work directly with Unicode characters.
• It has two super classes :
• Reader
• Writer

By : Prof. Nootan Padia 14


11/16/2018

Reader class
• It is an abstract class that defines Java’s model of streaming character
input.
• All of the methods throws IOException.
• Methods :-
abstract void close()
void mark(int numChars)
boolean markSupported()
int read()
void reset()
long skip(long numChars)

Writer class
• It is an abstract class that defines streaming character output.
• All of the methods return void and throw IOException.
• Methods :-
abstract void close()
abstract void flush()
void write(int ch)
void write(String str)
void write(String str, int offset, int numChars)

By : Prof. Nootan Padia 15


11/16/2018

FileReader & FileWriter class


• FileReader :-
• It creates a Reader that you can use to read the contents of a file.
• Constructors :-
FileReader(String filePath)
FileReader(File fileObj)
• FileWriter :-
• It creates a Writer that you can use to write to a file.
• Constructors :-
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)

BufferedReader & BufferedWriter classes


• BufferedReader :-
• It improves performance by buffering input.
• Constructors :-
BufferedReader(Reader inputStream)
BufferedReader(Reader inputStream, int bufSize)
• BufferedWriter :-
• It is a Writer that adds a flush() method that can be used to ensure that data buffers are
physically written to the actual output stream.
• Constructors :-
BufferedWriter(Writer outputstream)
BufferedWriter(Writer outputstream, int bufSize)

By : Prof. Nootan Padia 16


11/16/2018

PrintWriter class
• It is essentially a character-oriented version of PrintStream.
• It provides formatted output methods print() and println()
• Constructors :-
PrintWriter(OutputStream os)
PrintWriter(OutputStream os, boolean
flushOnNewLine)
PrintWriter(Writer os)
PrintWriter(Writer os, boolean
flushOnNewline)

Piped Streams
• We have two kinds of pipes. One is binary pipe and another is a
character pipe.
• The piped streams are used to have asynchronous data transfer
between the consumer of data and the producer of data.
• The producer of data would write data to the pipe and the consumer
of data would read the data from the pipe.

By : Prof. Nootan Padia 17


11/16/2018

• There are four kinds of piped stream :


• PipedInputStream
• PipedOutputStream
• PipedReader
• PipedWriter

• PipedOutputStream and PipedInputStream:-


• They are always used in pair.
• When a PipedOutputStream is connected to a PipedInputStream, it forms a
binary pipe.
• Constructors of PipedOutputStream :-
• public PipedOutputStream()
• public PipedOutputStream(PipedInputStream pin)

By : Prof. Nootan Padia 18


11/16/2018

• Constructors of PipedInputStream :-
• public PipedInputStream()
• public PipedInputStream(PipedOutputStream poe)
• The PipedOutputStream inherits all the methods of OutputStream and one
additional method called connect(). This method takes an instance of
PipedInputStream as a parameter and creates a pipe connecting a
PipedOutputStream with the specified PipedInputStream.

• The PipedInputStream inherits all the methods of InputStream and one


additional method called connect(). This method takes an instance of
PipedOutputStream as a parameter and creates a pipe connecting a
PipedInputStream with the specified PipedOutputStream.

By : Prof. Nootan Padia 19


11/16/2018

• PipedWriter and PipedReader :-


• They are always used in a pair.
• When a PipedWriter is connected to a PipedReader it forms a character pipe.
• A producer of text data can now write character data to the pipe using the
write() method on the PipedWriter and the consumer of text data can use the
connected PipedReader to read the character data from the pipe, which has
been written by the producer.

• Constructors of PipedWriter :-
• public PipedWriter()
• public PipedWriter( PipedReader pr)
• Constructors of PipedReader :-
• public PipedReader()
• public pipedReader( PipedWriter pw)
Both PipedReader and PipedWriter inherits methods from the Reader and
Writer classes respectively and both have additional connect() method.

By : Prof. Nootan Padia 20


11/16/2018

Array – based streams


• There are streams which use an array as a source or destination of
data.
• Streams are available for using byte[] as well as for char[].
• The output and input streams for byte[] are the
ByteArrayOutputStream and the ByteArrayInputStream.
• The output and input streams for char[] are the CharArrayWriter and
the CharArrayReader.

• ByteArrayInputStream
• ByteArrayInputStream is an implementation of an input stream that uses a
byte array as the source. This class has two constructors, each of which
requires a byte array to provide the data source:
• ByteArrayInputStream(byte array[ ])
• ByteArrayInputStream(byte array[ ], int start, int numBytes)

By : Prof. Nootan Padia 21


11/16/2018

• ByteArrayOutputStream
• ByteArrayOutputStream is an implementation of an output stream that uses
a byte array as the destination. ByteArrayOutputStream has two
constructors, shown here:
• ByteArrayOutputStream( )
• ByteArrayOutputStream(int numBytes)
• In the first form, a buffer of 32 bytes is created. In the second, a buffer is
created with a size equal to that specified by numBytes.

• CharArrayReader
• CharArrayReader is an implementation of an input stream that uses a
character array as the source. This class has two constructors, each of which
requires a character array to provide the data source:
• CharArrayReader(char array[ ])
• CharArrayReader(char array[ ], int start, int numChars)

By : Prof. Nootan Padia 22


11/16/2018

• CharArrayWriter
• CharArrayWriter is an implementation of an output stream that uses an
array as the destination. CharArrayWriter has two constructors, shown here:
• CharArrayWriter( )
• CharArrayWriter(int numChars)

What is 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.

By : Prof. Nootan Padia 23


11/16/2018

ObjectOutputStream
• ObjectOutputStream
• The ObjectOutputStream class extends the OutputStream class and
implements the ObjectOutput interface. It is responsible for writing objects
to a stream. A constructor of this class is
• ObjectOutputStream(OutputStream outStream) throws IOException
• The argument outStream is the output stream to which serialized objects will
be written.

ObjectOutput
• The ObjectOutput interface extends the DataOutput interface and supports object
serialization.
• Method Description
• void close( )
• void flush( )
• void write(byte buffer[ ])
• void write(byte buffer[ ], int offset, int numBytes)
• void write(int b) void writeObject(Object obj)

By : Prof. Nootan Padia 24


11/16/2018

ObjectInputStream
• ObjectInputStream
• The ObjectInputStream class extends the InputStream class and implements
the ObjectInput interface. ObjectInputStream is responsible for reading
objects from a stream. A constructor of this class is
• ObjectInputStream(InputStream inStream)
throws IOException, StreamCorruptedException
• The argument inStream is the input stream from which serialized objects
should be read.

• ObjectInput
• The ObjectInput interface extends the DataInput interface and defines the
methods.
• 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.

By : Prof. Nootan Padia 25


11/16/2018

• Method Description
• int available( )
• void close( )
• int read( )
• int read(byte buffer[ ])
• int read(byte buffer[ ], int offset,int numBytes)
• Object readObject( )
• long skip(long numBytes)

Bridge classes
• The two classes OutputStreamWriter and the InputStreamReader are
the character stream classes which are known as the bridge classes.
• These classes are the character based stream classes, but in turn work
on the byte – based streams.
• Since these are the character classes, they handle text made up of
unicode characters, but they also work on the byte streams, and this
would involve encoding and decoding characters from and to various
character sets.

By : Prof. Nootan Padia 26


11/16/2018

• Java.io.InputStreamReader Class
• The Java.io.InputStreamReader class is a bridge from byte streams to
character streams. It reads bytes and decodes them into characters using a
specified charset.
• Class declaration
• Following is the declaration for Java.io.InputStreamReader class:
• public class InputStreamReader extends Reader

S.N. Constructor & Description

1 InputStreamReader(InputStream in)
This creates an InputStreamReader that uses the default
charset.
2 InputStreamReader(InputStream in, Charset cs)
This creates an InputStreamReader that uses the given
charset.
3 InputStreamReader(InputStream in, CharsetDecoder
dec)
This creates an InputStreamReader that uses the given
charset decoder.
4 InputStreamReader(InputStream in, String charsetName)
This creates an InputStreamReader that uses the named
charset.

By : Prof. Nootan Padia 27


11/16/2018

S.N. Method & Description

1 void close()
This method closes the stream and releases any system
resources associated with it.
2 String getEncoding()
This method returns the name of the character encoding
being used by this stream.
3 int read()
This method reads a single character.
4 int read(char[] cbuf, int offset, int length)
This method reads characters into a portion of an array.
5 boolean ready()
This method tells whether this stream is ready to be read.

• Java.io.OutputStreamWriter Class
• The Java.io.OutputStreamWriter class is a bridge from character streams to
byte streams. Characters written to it are encoded into bytes using a specified
charset.
• Class declaration
• Following is the declaration for Java.io.OutputStreamWriter class:
• public class OutputStreamWriter extends Writer

By : Prof. Nootan Padia 28


11/16/2018

S.N. Constructor & Description


1 OutputStreamWriter(OutputStream out)
This creates an OutputStreamWriter that uses the
default character encoding.
2 OutputStreamWriter(OutputStream out, Charset cs)
This creates an OutputStreamWriter that uses the given
charset.
3 OutputStreamWriter(OutputStream out,
CharsetEncoder enc)
This creates an OutputStreamWriter that uses the given
charset encoder.
4 OutputStreamWriter(OutputStream out, String
charsetName)
This creates an OutputStreamWriter that uses the
named charset.

S.N. Method & Description

1 void close()
This method closes the stream, flushing it first.
2 void flush()
This method flushes the stream.
3 String getEncoding()
This method returns the name of the character encoding
being used by this stream.
4 void write(char[] cbuf, int off, int len)
This method writes a portion of an array of characters.
5 void write(int c)
This method writes a single character.
6 void write(String str, int off, int len)
This method writes a portion of a string.

By : Prof. Nootan Padia 29


11/16/2018

Byte-Oriented Input Stream Classes


The following is the byte-oriented input stream class hierarchy:

InputStream

ByteArrayInputStream FileInputStream SequenceInputStream

ObjectInputStream PipedInputStream
FilterInputStream

BufferedInputStream DataInputStream PushbackInputStream

Byte-Oriented Output Stream


Classes
The following is the byte-oriented input stream class hierarchy:

OutputStream

PipedOutputStream
ByteArrayOutputStream FileOutputStream

ObjectOutputStream
FilterOutputStream

BufferedOutputStream DataOutputStream PrintStream

ZipOutputStream ZipOutputStream is defined in: java.util.zip

By : Prof. Nootan Padia 30


11/16/2018

Character-Oriented Reader Classes


The following is the byte-oriented input stream class hierarchy:

Reader

PipedReader CharArrayReader StringReader

BufferedReader FilterReader InputStreamReader

LineNumberReader PushbackReader FileReader

Character-Oriented Writer Classes


The following is the byte-oriented input stream class hierarchy:

Writer

PipedWriter
CharArrayWriter FileWriter StringWriter

BufferedWriter OutputStreamWriter PrintWriter

FileWriter

By : Prof. Nootan Padia 31

You might also like