0% found this document useful (0 votes)
24 views

Unit IV Io1

This document discusses Java I/O streams. It describes byte streams and character streams. It also explains input streams and output streams, and how they are used to read from and write to various sources and destinations like files, networks, and devices.

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Unit IV Io1

This document discusses Java I/O streams. It describes byte streams and character streams. It also explains input streams and output streams, and how they are used to read from and write to various sources and destinations like files, networks, and devices.

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

Unit -IV

This work is created by N.Senthil madasamy, Dr. A.Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
Introduction
• Working with java.io.* package
• Operates with external data
• Data is retrieved from input Source
• Results are send to output Destination
• Sources and Destination devices:
– Network connection, memory buffer, or disk file
• These devices handles data as: Stream
Handling Files
• File class does not operate with input and
output streams
– i.e.., File class does not specify how
information is retrieved from or stored in
files
• File object only maintains:
– File permissions, time, date, and directory
path
Constructors in File
• File(String directoryPath)
• File(String directoryPath, String filename)
• File(File dirObj, String filename)
• File(URI uriObj)

Some other methods:


• getName( )  Returns the name of the file
• getParent( )  Returns the name of directory
• exists( ) returns true if the file exists, else false
Some other utility methods…
• boolean renameTo(File newName);
– Invoking file is renamed and returns true if success
• boolean delete( );
– Deletes the invoking file
• long lastModified( );
– Returns the time in milliseconds representing last
modified time
• int length( );
– Returns the length in bytes.
• File f1 = new File("/java/COPYRIGHT.txt");

f1.getName() COPYRIGHT.txt
f1.getPath() \java\COPYRIGHT.txt
f1.getAbsolutePath() C:\java\COPYRIGHT.txt
f1.getParent() \java
f1.exists() True
f1.canWrite() True
f1.canRead() True
f1.isDirectory() False
f1.isFile() True
f1.lastModified() 1282832030047
f1.length() 695 Bytes
Some other methods…
Directories
• A directory is a File that contains a list of other
files and directories
• Methods:
– boolean isDirectory( )  checks if the invoking
object is a directory
– String[ ] list( )  returns the names of all files and
directories inside the invoking directory
Write a java program to list only java files
import java.io.*;
class DirList1 {
public static void main(String args[])
{
String dirname = "G:/MCET/java/example";
File f1 = new File(dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
if(s[i].endsWith(“java”)) System.out.println(s[i]);
}
}
Using Filename Filter
• Used to filter the list of files returned by list()
function
• Hence returning only those files that match a
certain filename pattern
String[ ] list(FilenameFilter FFObj)
• FilenameFilter  A file interface
– Which calls:
boolean accept(File directory, String filename)
import java.io.*;
class DirList implements FilenameFilter{
String ext;
DirList(String s) { ext=s; }
public boolean accept(File dir, String name)
{ return name.endsWith(ext); }
public static void main(String args[])
{
String dirname = "G:/MCET/java/example";
File f1 = new File(dirname);
FilenameFilter only = new DirList("java");
String s[] = f1.list(only);
for (int i=0; i < s.length; i++) { System.out.println(s[i]);}
}
}
listFiles() method
• This method returns a list of “File” instances
inside a directory
• Constructors:
– File[ ] listFiles( )
– File[ ] listFiles(FilenameFilter FFObj)
– File[ ] listFiles(FileFilter FObj)
Creating Directories
• Methods used to create directories:
– mkdir( )  creates a directory, returning true on
success and false on failure
• False is returned if the path is not properly specified; or
path already exists
– mkdirs( )  creates a directory for which no path
exists
• Ie.., It creates both a directory and all the parents of
the directory
The Closeable and Flushable Interfaces

• Released in JDK 5
• They offer a uniform way of specifying that a
stream can be closed or flushed
• void close( )
– This method closes the invoking stream, releasing
any resources that it may hold
• void flush( )
– Force buffered output to be written to the stream
to which the object is attached
Stream
Stream
• A stream is an abstraction, which either produces or
consumes information
• A stream is a sequence of bytes that flows into or out of
your program.
• A stream is linked to a physical device by the Java I/O
system.
• The input stream gets input from a disk file, a keyboard
or a network socket.
• The output stream refers to the console, a disk file or a
network connection.
• To use stream classes, you must import java.io package.
Stream
Two types of streams:
• Byte Stream
• Character Stream
• Stream I/P and O/P methods generally permits
very small amounts of data (such as single char
or byte) to be written or read in a single
operation.
• Sending data transfers like this to a physical
device would be extremely inefficient.
• So a stream is often prepared with a “Buffer”,
and it is called a “Buffered Stream”.
• A buffer is simply a block of memory that is
used to batch up data transfers to or from an
external device.
Stream Input/Output operations:
• When you write data to a stream as a series of bytes
(i.e., binary data), it is written to the stream exactly
as it appears in memory.
• No transformations of the data take place.
Numerical values are just written as a series of
bytes.
• When you write data to a stream as a series of
characters, all numeric data is converted to a textual
representation before being written to the stream.
• This involves formatting the data to generate a
character representation of the data value.
Stream Input/Output operations:

• Reading numeric data from a character stream


involves much more work than reading binary
data.
• You must determine how many characters
make up a single numeric value.
• You need to recognize where each numerical
value begins and ends.
• Convert the value to the corresponding binary
form.
Stream Input/Output operations:

Total of 5 bytes written

ASCII representation of
characters
‘1’ ‘6’ ‘7’ ‘2’ ‘7’

Stream content
Ox31 Ox36 Ox37 Ox32 Ox37

To read these back successfully, you


int A=167; OxA7 Write A need to know that the 1st three bytes
corresponds to A and the next two
bytes corresponds to B.
Write B
int B=27; Ox1B
Java I/O
• Java I/O is designed based on 4 abstract
classes:
– InputStream For Byte Stream
– OutputStream
– Reader
For Character Stream
– Writer
• Use Character stream – while working with
string/ chars; Byte Stream – other binary
objects
Byte Stream
• Byte streams are defined by 2 abstract classes.
InputStream Base classes for all other byte stream
subclasses.
OutputStream

• InputStream and OutputStream: Define several methods.


• Most important methods: read () and write (), which
read and write byte of data.
• These methods are declared as abstract inside the
InputStream and OutputStream. They are overridden by
derived stream classes.
OutputStream vs InputStream
OutputStream vs InputStream
OutputStream
• Java application uses an output stream to
write data to a destination, it may be a file, an
array, peripheral device or socket.
InputStream
• Java application uses an input stream to read
data from a source, it may be a file, an array,
peripheral device or socket.
It contains an internal buffer It is a piped input stream that can
which is used to read byte be connected to a piped output
array as stream stream to create a communications
Java ByteArrayInputStream pipe
class contains an internal
buffer which is used to read
byte array as stream.
It is used for reading byte-
oriented data (streams of raw
It is the super class of
bytes) such as image data, all classes that filter
audio, video etc. input streams

It can unread a byte which is already


read and push back one byte.
lets an application read
primitive Java data types
from an intput stream in
a portable way Classes are
loaded as required using the
standard mechanisms

It is used to recover those objects previously serialized. It ensures that


class is used to read information from stream. It the types of all objects in the graph created from the stream match the
internally uses buffer mechanism to make the classes present in the Java Virtual Machine. Classes are loaded as
performance fast.Classes are loaded as required required using the standard mechanisms
using the standard mechanisms
Byte Stream
InputStream Methods:
• public abstract int read( ) throws java.io.IOException;
– read a single byte from an input stream. Returns an
integer representation of the next available byte of
input.
– If the end of the file is encountered, then it returns -
1.
Byte Stream
InputStream Methods:
• public int read( byte buffer[ ] ) throws java.io.IOException;
• Read up to buffer.length() bytes in to buffer and
returning the number of bytes successfully read.
–1 is returned when the end of file is encountered.
Byte Stream
InputStream Methods:
• public int available ( ) throws java.io.IOException;
• Return the number of bytes of input currently
available for reading.
Byte Stream
InputStream Methods:
• public void close( ) throws java.io.IOException;
• Close the input source. Further read attempts
will generate an IOException.
It is used to write It is the super class of all classes
common data into that filter output streams
multiple files
It is a piped output stream
It is an output stream used that can be connected to a
for writing data to a file. piped input stream to
create a communications
pipe

the ability to print


It helps to write representations of various data
primitive Java data values conveniently.
types to an output
stream in a
portable way .
Classes are loaded
as required using
the standard
mechanisms It is used to recover those objects previously serialized. It
ensures that the types of all objects in the graph created
from the stream match the classes present in the Java
Virtual Machine.Classes are loaded as required using the
standard mechanisms
It is used to recover those objects previously serialized. It ensures that the types of all
objects in the graph created from the stream match the classes present in the Java
Virtual Machine.
Byte Stream
OutputStream Methods:
• public void abstract write( byte ) throws
java.io.IOException;
– Write a single byte to an output stream.
Byte Stream
OutputStream Methods:
• public void write( byte buffer[ ] ) throws
java.io.IOException;
– Write a complete array of bytes to an output
stream.
Byte Stream
OutputStream Methods:
• public void write( byte buffer[ ], int offset, int
numBytes ) throws java.io.IOException;
 Write a sub range of ‘numBytes’ bytes from
the array buffer, beginning at buffer[offset].
Byte Stream
OutputStream Methods:
• public void close( ) throws java.io.IOException;
 Close the output stream. Further write
attempts will generate an IOException.
Byte Stream
OutputStream Methods:
• public void flush( ) throws java.io.IOException;
 Flushes output buffers. (Output buffers are
cleared)
FileInputStream

• To read data from a file byte wise.


• It throws FileNotFoundException.
Constructors:
• FileInputStream (String filePath)
• FileInputStream (File fileObject)
– Where filePath is full path name of a file.
– fileObject is a File object that describes the path
of a file.
FileOutputStream

• To write data to a file byte wise.


• It throws FileNotFoundException. Or SecurityException
Constructors:
• FileOutputStream (String filePath)
• FileOutputStream (File fileObject)
• FileOutputStream (String filePath, boolean append)
– Where filePath is full path name of a file.
– fileObject is a File object that describes the path of a file.
– If append is true, then the file is opened in append mode.
– If append is false, then the file is opened in overwrite mode.
BufferedOutputStream Class
• Java BufferedOutputStream class is used for
buffering an output stream.
• It internally uses buffer to store data. It adds
more efficiency than to write data directly into a
stream. So, it makes the performance fast.
class declaration
public class BufferedOutputStream extends
FilterOutputStream
BufferedOutputStream -constructors
Constructor Description
BufferedOutputStream(OutputStream os) It creates the new buffered output
stream which is used for writing the
data to the specified output stream.
BufferedOutputStream(OutputStream os, int size) It creates the new buffered output
stream which is used for writing the
data to the specified output stream
with a specified buffer size.

class methods
Method Description
void write(int b) It writes the specified byte to the buffered output
stream.
void write(byte[] b, int off, int len) It write the bytes from the specified byte-input
stream into a specified byte array, starting with
the given offset
void flush() It flushes the buffered output stream.
BufferedInputStream Class

• Java BufferedInputStream class is used to read information


from stream. It internally uses buffer mechanism to make the
performance fast.

The important points about BufferedInputStream are:


• When the bytes from the stream are skipped or read, the
internal buffer automatically refilled from the contained input
stream, many bytes at a time.
• When a BufferedInputStream is created, an internal buffer
array is created.

public class BufferedInputStream extends FilterInputStream


BufferedInputStream class constructors

BufferedInputStream(InputStream IS)

It creates the BufferedInputStream and saves


it argument, the input stream IS, for later use.

BufferedInputStream(InputStream IS, int size)


It creates the BufferedInputStream with a
specified buffer size and saves it argument,
the input stream IS, for later use.
Java BufferedInputStream class methods
int available(),
InputStream
int read(),
void close(),
void reset()
boolean markSupported()
void mark(int readlimit)
int read(byte[] b) FilterInputStream
long skip(long x)

int read(byte[] b, int off, int ln)


It read the bytes from the specified byte-input stream into a
specified byte array, starting with the given offset.
Example of BufferedOutputStream
import java.io.*;
public class BufferedOutputStreamExample{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);
String s="Welcome to CSE.";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
System.out.println("success");
}
}
Example of BufferedInputStream
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
DataOutputStream Class

• Java DataOutputStream class allows an


application to write primitive Java data types to
the output stream in a machine-independent
way.
• Java application generally uses the data output
stream to write data that can later be read by a
data input stream.
public class DataOutputStream extends
FilterOutputStream implements DataOutput
Method Description
DataOutputStream class methods

int size() It is used to return the number of


bytes written to the data output
stream.
void write(int b) It is used to write the specified byte
to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to
the output stream.
void writeChar(int v) It is used to write char to the output
stream as a 2-byte value.
void writeChars(String s) It is used to write string to the
output stream as a sequence of
characters.
void writeByte(int v) It is used to write a byte to the
output stream as a 1-byte value.
Method Description
DataOutputStream class methods

void writeBytes(String s) It is used to write string to the output stream


as a sequence of bytes.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output
stream.
void writeShort(int v) It is used to write a short to the output
stream.
void writeLong(long v) It is used to write a long to the output
stream.
void writeUTF(String str) It is used to write a string to the output
stream using UTF-8 encoding in portable
manner.
void flush() It is used to flushes the data output stream.
DataInputStream Class

• Java DataInputStream class allows an application to


read primitive data from the input stream in a
machine-independent way.
• Java application generally uses the data output
stream to write data that can later be read by a
data input stream.
public class DataInputStream extends FilterInputStrea
m implements DataInput
Java DataInputStream class methods
int available(),
InputStream
int read(),
void close(),
void reset()
void reset()
boolean markSupported()
void mark(int readlimit) FilterInputStream
int read(byte[] b)
long skip(long x)

int read(byte[] b, int off, int ln)


It read the bytes from the specified byte-input stream into a
specified byte array, starting with the given offset.
Java DataInputStream class methods
int readInt()
byte readByte() Helps to single read
int,byte,char,double ,boolean values
char readChar()
from stream class
double readDouble()
boolean readBoolean()

int skipBytes(int x)
-Skips to byte n bytes
void readFully(byte[] b)
It is used to read input bytes and return an int value.
void readFully(byte[] b, int off, int len)
it is used to read len bytes from the input stream.
Example of DataOutputStream class

import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
DataInputStream Class

import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (int i=0;i<ary.length;i++) {
char k = (char) ary[i];
System.out.print(k);
}
PushbackInputStream
• The Java.io.PushbackInputStream class adds
functionality to another input stream, namely
the ability to "push back" or "unread" one
byte.
public class PushbackInputStream extends
FilterInputStream
Constructor
• PushbackInputStream(InputStream in)
– This creates a PushbackInputStream and saves its
argument, the input stream in, for later use.
• PushbackInputStream(InputStream in, int
size)
– This creates a PushbackInputStream with a
pushback buffer of the specified size, and saves its
argument, the input stream in, for later use.
• 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.
• void close() This method closes this input
stream and releases any system resources
associated with the stream.
• void mark(int readlimit) This method marks
the current position in this input stream.
• int read() This method reads the next byte of
data from this input stream.
• 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.
• void reset() This method repositions this
stream to the position at the time the mark
method was last called on this input stream.
• long skip(long n) This method skips over and
discards n bytes of data from this input
stream.

EXAMPLE
PushbackInputStream input ;
Input = new PushbackInputStream(
new FileInputStream(“input.txt"));
int data = input.read();
The call to read() reads a byte just like
input.unread(data); from an InputStream.

The call to unread() pushes a byte


back into the PushbackInputStream.

The next time read() is called the


pushed back bytes will be read first.
Setting the Push Back Limit
int pushbackLimit = 8;
PushbackInputStream input = new PushbackInputStream( new
FileInputStream("c:\\data\\input.txt"), pushbackLimit);

This example sets an internal buffer of 8 bytes. That


means you can unread at most 8 bytes at a time,
before reading them again
PrintStream Class

• The PrintStream class provides methods to


write data to another stream.
• The PrintStream class automatically flushes the
data so there is no need to call flush() method.
• Moreover, its methods don't throw
IOException.
public class PrintStream extends FilterOutputStre
am implements Closeable. Appendable
PrintStream Class

Method Description
void print(char c) It prints the specified char value.
void println(char c)

void print(char[] c) It prints the specified character array values.


void println(char[] c)

void print(int i) It prints the specified int value.


void println(int i)

void print(long l) It prints the specified long value.


void println(long l)

void print(float f) It prints the specified float value.


void println(float f)

void print(String s) It prints the specified string value.


void print(String s)
PrintStream Class
printing integer and string value.

import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");
PrintStream pout=new PrintStream(fout);
pout.println(2016);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
System.out.println("Success?");
}
RandomAccessFile:

• It is derived from InputStream and OutputStream.


• It implements the interfaces DataInput and DataOutput, which define
the basic I/O methods.
• It also supports positioning the file pointer within the file.
Constructors:
• RandomAccessFile (File fileObject, String access) throws
FileNotFoundException
• RandomAccessFile (String fileName, String access) throws
FileNotFoundException
– fileObject specifies the name of the file as a File object.
– fileName specifies the name of the file as string.
– ‘access’ determines what type of file access is permitted. If it is “r”, then the file
opened in read-only mode. If it is “rw”, the file is opened in read-write mode.
RandomAccessFile:

Methods:
• void seek( long newPosition) throws IOException;
– Used to set the current position of the file pointer.
– ‘newPosition’ specifies the new position (in bytes) of the
file pointer from the beginning of the file. After a call to
seek(), the next read/write operation will occur at the new
file position.
RandomAccessFile:

Methods:
• long getFilepointer()
– Return the current position of the file
pointer.
RandomAccessFile:
import java.io.*;
class RandomFileExample
{
public static void main(String[] args)
{
try
{

RandomAccessFile file = new RandomAccessFile("std.dat","rw");

file.setLength(0);

for(int i=0;i<50;i++) file.writeInt(i);

System.out.println("Length of File After Writing :"+file.length());

file.seek(0); System.out.println("First Number is : "+file.readInt());

file.seek(1*4); System.out.println("Second Number is : "+file.readInt());

file.writeInt(101); file.seek(file.length());

file.writeInt(50); System.out.println("Current Length of File is : "+file.length());


}
catch(Exception e) { }
}
}
RandomAccessFile:
import java.io.*;
class RandomFileExample
{
public static void main(String[] args)
{
try
{

RandomAccessFile file = new RandomAccessFile("std.dat","rw");

file.setLength(0);

for(int i=0;i<50;i++) file.writeInt(i);

System.out.println("Length of File After Writing :"+file.length());

file.seek(0); System.out.println("First Number is : "+file.readInt());

file.seek(1*4); System.out.println("Second Number is : "+file.readInt());

file.writeInt(101); file.seek(file.length());

file.writeInt(50); System.out.println("Current Length of File is : "+file.length());


}
catch(Exception e) { }
}
}
Character Stream
• Used for reading and writing character data.
• Character streams are more efficient than byte streams.
• Character streams are defined by 2 abstract classes.
– Reader
– Writer.
• The Reader and Writer are base class for all other character
stream subclasses
• The abstract classes Reader and Writer define several methods
that the other stream classes implement.
• Two of the most important methods are read() and write(),
which read and write characters of data.
• These methods are declared as abstract inside the Reader and
Writer. They are overridden by derived stream classes.
Reader Sub Classes
• BufferedReader Buffered input character
stream.
• CharArrayReader input stream that reads
from a character array.
• FileReader input stream that reads from a
file.
Reader Class Methods

• public int read( ) throws IOException;


 Read a single character. Return the next available
character of input.
–1 is returned when the end of the file is
encountered.
• public int read( char buffer[ ] ) throws IOException;
 Read up to buffer.length () characters in to buffer
and returning the number of characters successfully
read.
–1 is returned when the end of file is encountered.
Reader Class Methods:

• public void reset( ) throws IOException;


 File pointer goes to beginning of the file.

• public long skip( long numChars ) throws


IOException;
•  Ignores (i.e., skips) ‘numChars’ of input and
returning the number of characters actually
ignored
Reader Class Methods

public boolean ready( ) throws IOException;


 Returns true if the next input request is
ready. Otherwise, it returns false.
public abstract void close( ) throws
IOException;
 Close the input source. Further read
attempts will generate an IOException
Writer Sub Classes
• BufferedWriter buffered output character
stream.
• CharArrayWriter output stream that writes
to a character array.
• FileWriter output stream that writes to a
file.
Writer Class Methods
public void write( char ) throws IOException;
 Write a single character to an output
stream.
public void write( char buffer[ ] ) throws
IOException;
 Write a complete array of characters to an
output stream.
Writer Class Methods
public void write( String str ) throws IOException;
 Write str to the invoking output stream.
public abstract void close( ) throws IOException;
 Close the output stream. Further write
attempts will generate an IOException.
public abstract void flush( ) throws IOException;
 Flushes output stream buffers. (Output
buffers are cleared)
FileReader

• To read data from a file character wise.


• It throws FileNotFoundException
• Constructors:
• FileReader ( String filePath)
• FileReader ( File FileObject)
– Where filePath is full path name of a file.
– fileObject is a File object that describes the path of
a file.
FileWriter
• To write data to a file character wise.
• It throws FileNotFoundException
• Constructors:
• FileWriter( String filePath)
• FileWriter( File FileObject)
• FileWriter( String filePath, boolean append)
• Where filePath is full path name of a file.
• fileObject is a File object that describes the path of a file.
• If append is true, then the file is opened in append mode.
• If append is false, then the file is opened in over write mode.
import java.io.*;
class Copyfile1
{
public static void main(String arg[]) throws Exception
{
int i;
try {
FileReader Fin;FileWriter Fout;
Fin=new FileReader(arg[0]); Fout=new FileWriter(args[1]);

do
{ i=Fin.read(); if(i==-1) break;
Fout.write(i);
}while(i != -1);
Fin.close(); Fout.close();
} catch(FileNotFoundException e)
{ System.out.println("Error: Does not found output file"+ e);}
}
}

You might also like