0% found this document useful (0 votes)
22 views37 pages

Streams

streams

Uploaded by

Adiba Fatima
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)
22 views37 pages

Streams

streams

Uploaded by

Adiba Fatima
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/ 37

Java Programming

II B.Tech II-Sem IT
Unit-II
java.io
The Java I/O Classes and Interfaces:
The Java I/O Classes and Interfaces:
File:
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.

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)
Some methods in File class:

boolean canRead( ) int hashCode( )


boolean canWrite( ) boolean isDirectory( )
int compareTo(File pathname) boolean isFile( )
boolean createNewFile( ) boolean isHidden( )
boolean delete( ) long lastModified( )
void deleteOnExit( ) long length( )
boolean equals(Object obj) String[ ] list( )
boolean exists( ) File[ ] listFiles( )
String getName( ) boolean mkdir( )
String getParent( ) boolean renameTo(File dest)
File getParentFile( ) boolean setLastModified(long time)
String getPath( ) boolean setReadOnly( )
String toString( )
import java.io.File;
class FileDemo
{
public static void main(String[] args)
{
String fname = args[0];
File f = new File(fname);
System.out.println("File name :" + f.getName());
System.out.println("Path: " + f.getPath());
System.out.println("Absolute path:"
+ f.getAbsolutePath());
System.out.println("Parent:" + f.getParent());
System.out.println("Exists :" + f.exists());

if (f.exists()) {
System.out.println("Is writable:"
+ f.canWrite());
System.out.println("Is readable:" + f.canRead());
System.out.println("Is a directory:"
+ f.isDirectory());
System.out.println("File Size in bytes "
+ f.length());
}
}
}
RandomAccessFile

This class allows the reading and writting of data to any location in the file
respectively. It is used to read and write data simultaneously i.e. we can read
the file, write to a file, and move the file pointer to another location in the
same program.The following are the constructors of RandomAccess File
class:

RandomAccessFile(File file, String mode)


RandomAccessFile(String name, String mode)

The first creates a random access file stream to read from, and optionally to
write to, the file specified by the File argument and the second one creates a
random access file stream to read from, and optionally to write to, a file with
the specified name.
S.No. Methods with Description
1 int read()
It reads byte of data from a file. The byte is returned as an integer in the range 0-255.
2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.
3 int read(byte[] b, int offset, int len)
It reads bytes initialising from offset position upto b.length from the buffer.
4 boolean readBoolean()
It reads a boolean value from from the file.
5 byte readByte()
It reads signed eight-bit value from file.
6 char readChar()
It reads a character value from file.
7 double readDouble() and float readFloat()
It reads a double and a float respectively value from file.
8 long readLong() and int readInt()
It reads a long and integer value respectively from file.
9 void readFully(byte[] b)
It reads bytes initialising from offset position upto b.length from the buffer.
10 void readFully(byte[] b, int offset, int len)
It reads bytes initialising from offset position upto b.length from the buffer.
11 String readUTF()
t reads in a string from the file.
12 void seek(long pos)
It sets the file-pointer(cursor) measured from the beginning of the file, at which the next
read or write occurs.
13 long length()
It returns the length of the file.
14 void write(int b)
It writes the specified byte to the file from the current cursor position.
15 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class Float, and
then writes that int value to the file as a four-byte quantity, high byte first.
16 void writeDouble(double v):It converts the double argument to a long using the
doubleToLongBits method in class Double, and then writes that long value to the file as
an eight-byte quantity, high byte first.
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
// create a new RandomAccessFile with filename test
RandomAccessFile raf = new RandomAccessFile
("C:/Users/hp/Desktop/JAVA/JavaPrograms/Sample1.java", "rw");
System.out.println("Length of File is "+raf.length());
raf.writeUTF("Hello World"); // write something in the file
raf.seek(0); // set the file pointer at 0 position
// print the string
System.out.println("" + raf.readUTF());
// set the file pointer at 5 position
raf.seek(5);
// write something in the file
raf.writeUTF("This is an example");

// set the file pointer at 0 position


raf.seek(0);

// print the string


System.out.println("" + raf.readUTF());
System.out.println("Length of File is "+raf.length());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
UNIT-IV 14
The Java I/O Streams:
In Java, input and output is defined in terms of an abstract concept
called "stream".

A stream is a sequence of data.

If it is an input stream, it has source.

If it is an output stream, it has a destination.

There are two kinds of streams:

byte streams

character streams

The java.io package provides a large number of classes to perform


stream I/O.
Byte streams and Character streams:

Java’s stream-based I/O is built upon four abstract classes:

InputStream

OutputStream

Reader

Writer

InputStream and OutputStream are designed for byte streams.

Reader and Writer are designed for character streams.


The Java I/O Classes and Interfaces:
InputStream class:
Methods of InputStream class:

int available( )
void close( )
void mark(int readlimit)
boolean markSupported( )
abstract int read( )
int read(byte[ ] b)
int read(byte[ ] b, int off, int len)
void reset( )
long skip(long n)
Class FileInputStream:

A FileInputStream obtains input bytes from a file in a file system.

Constructors:
FileInputStream(File file)
FileInputStream(String name)

Some methods:

int available( )
void close( )
protected void finalize( )
int read( )
int read(byte[ ] b)
int read(byte[ ] b, int off, int len)
long skip(long n)
FileInputStream: Example program
import java.io.*;
class FileInputStreamDemo
{
public static void main(String args[ ]) throws IOException
{
FileInputStream f1=new FileInputStream("Sample.java");
int a=f1.available( );
System.out.println("Total Available bytes:"+a);
for(int i=1;i<=a;i++)
System.out.print((char)f1.read( ));
f1.close( );
FileInputStream f2=new FileInputStream("Sample.java");
byte b[ ]=new byte[20];
int x=f2.read(b);
for(int i=0;i<b.length;i++)
System.out.print((char)b[i]);
f2.close( );
}
}
Class ByteArrayInputStream:
A ByteArrayInputStream contains an internal buffer(byte array) that
contains bytes that may be read from the stream.
Constructors:
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)

Some methods:
int available( )
void close( )
void mark(int readAheadLimit)
boolean markSupported( )
int read( )
int read(byte[ ] b, int off, int len)
void reset( )
long skip(long n)
ByteArrayInputStream: Example Program
import java.io.*;
class ByteArrayInputStreamDemo
{
public static void main(String args[ ]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[ ] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3);
int c;
while ((c = input1.read( )) != -1)
{
System.out.print((char) c);
}
while ((c = input2.read( )) != -1)
{
System.out.print((char) c);
}
}
}
Filtered Byte Streams:

This class is the superclass of all classes that filter input streams.

These streams sit on top of an already existing input stream


(the underlying input stream), but provide additional functionality.

The class FilterInputStream itself simply overrides all methods of


InputStream with versions that pass all requests to the underlying
input stream.

Subclasses of FilterInputStream may further override some of these


methods as well as provide additional methods and fields.
BufferedInputStream:

The class implements a buffered input stream.

By setting up such an input stream, an application can read bytes from a


stream without necessarily causing a call to the underlying system for each
byte read.

The data is read by blocks into a buffer; subsequent reads can access
the data directly from the buffer.

Constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)

BufferedInputStream also supports the mark( ) and reset( ) methods.


BufferedInputStream: Example Program

import java.io.*;
class BufferedInputStreamDemo
{
public static void main(String args[]) throws IOException
{
String s = "THIS ON BUFFEREDINPUTSTREAM CLASS";
byte buf[ ] = s.getBytes( );
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream(in);
boolean m=f.markSupported( );
System.out.println("Mark:"+m);
}
}
OutputStream class:
Methods of OutputStream class:

void close( )
void flush( )
void write(byte[ ] b)
void write(byte[ ] b, int off, int len)
abstract void write(int b).
FileOutputStream:

A file output stream is an output stream for writing bytes to a file.

Constructors:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
FileOutputStream: Example program

import java.io.*;
class FileOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
FileOutputStream f1=new FileOutputStream("Sample.java");
byte b[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
f1.write(65);
f1.write(b);
f1.close();
FileOutputStream f2=new FileOutputStream("Sample.java",true);
f2.write(65);
f2.write(b);
f2.close();
}
}
ByteArrayOutputStream:
ByteArrayOutputStream is an implementation of an output stream
that uses a byte array as the destination.
Constructors:
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.

The buffer is held in the protected buf field of ByteArrayOutputStream.

The buffer size will be increased automatically, if needed.

The data can be retrieved using toByteArray( ) and toString( ).


ByteArrayOutputStream: Example program

import java.io.*;
class ByteArrayOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream bs1 = new ByteArrayOutputStream( );
String s = "This should end up in the array";
byte buf[ ] = s.getBytes( );
bs1.write(buf);
System.out.println("Buffer as a string");
System.out.println(bs1.toString( ));
bs1.close( );
}
}
BufferedOutputStream:

The class implements a buffered output stream.

By setting up such an output stream, an application can write bytes to the


underlying output stream without necessarily causing a call to the
underlying system for each byte written.

The data is written into a buffer, and then written to the underlying stream
if the buffer reaches its capacity, the buffer output stream is closed,
or the buffer output stream is explicity flushed.

Constructors:
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)
Reader class:
Methods of Reader class:

abstract void close( )


void mark(int readAheadLimit)
boolean markSupported( )
int read( )
int read(char[ ] cbuf)
abstract int read(char[ ] cbuf, int off, int len)
boolean ready( )
void reset( )
long skip(long n)
Writer class:
Methods of Writer class:

abstract void close( )


abstract void flush( )
void write(char[ ] cbuf)
abstract void write(char[ ] cbuf, int off, int len)
void write(int c)
void write(String str)
void write(String str, int off, int len)

You might also like