7.FileHandling - Bytestream
7.FileHandling - Bytestream
7.FileHandling - Bytestream
File Handling
I/O in JAVA
○ Java I/O (Input and Output) is used to process the input and produce the output.
○ Java uses the concept of stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.
● In java, 3 streams are created for us automatically. All these streams are
attached with console.
DataInput The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java
primitive types.
DataOutput The DataOutput interface provides for converting data from any of the Java primitive types to a series of bytes and writing these
bytes to a binary stream.
Externalizable Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class
to save and restore the contents of its instances.
FilenameFilter Instances of classes that implement this interface are used to filter filenames.
ObjectInput ObjectInput extends the DataInput interface to include the reading of objects.
Serializable Serializability of a class is enabled by the class implementing the java.io.Serializable interface.
I-O STREAM CLASSES IN JAVA
Java provides java.io package which contains a large number of stream classes to process all types of data:
● Byte stream classes
○ Support for handling I/O operations on bytes
● Character stream classes
○ Supports for handling I/O operations on characters
Methods in Byte Stream (input) classes
Method Description
read(byte b[ ], int n, int m) Reads m bytes into b starting from nth byte
readShort( ) readDouble( )
readInt( ) readLine( )
readLong( ) readChar( )
readFloat( ) readBoolean( )
readUTF( )
Methods in Byte Stream (output) classes
Method Description
write (byte b[ ]) Write all bytes in the array b to the output steam
write (byte b[ ], int n, Write m bytes from array b starting from nth byte
int m)
writeShort( ) writeDouble( )
writeInt( ) writeLine( )
writeLong( ) writeChar( )
writeFloat( ) WriteBoolean( )
writeUTF( )
Methods in Character Stream (reader) classes
Method Description
close() Closes the stream and releases any system resources associated with it.
mark(int readAheadLimit) Tells whether this stream supports the mark() operation.
read(char[] cbuf, int off, int len) Reads characters into a portion of an array.
read(CharBuffer target) Attempts to read characters into the specified character buffer.
append(CharSequence csq, int start, int end) Appends a subsequence of the specified character sequence to this writer.
write(char[] cbuf, int off, int len) Writes a portion of an array of characters.
Note:
InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.
public abstract class InputStream extends Object implements Closeable
Classes under InputStream class
Class Description
BufferedInputStream A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to
support the mark and reset methods.
ByteArrayInputStream A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.
DataInputStream A data input stream lets an application read primitive Java data types from an underlying input stream in a
machine-independent way.
PipedInputStream A piped input stream should be connected to a piped output stream; the piped input stream then provides
whatever data bytes are written to the piped output stream.
ObjectInputStream An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.
Methods
available() 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.
close() Closes this input stream and releases any system resources associated with the stream.
markSupported() Tests if this input stream supports the mark and reset methods.
read() Reads the next byte of data from the input stream.
read(byte[] b) Reads some number of bytes from the input stream and stores them into the buffer array b.
read(byte[] b, int off, int len) Reads up to len bytes of data from the input stream into an array of bytes.
reset() Repositions this stream to the position at the time the mark method was last called on this
input stream.
skip(long n) Skips over and discards n bytes of data from this input stream.
InputStream classes is used to read 8-bit bytes and supports a number of input-related methods
● Reading bytes
● Closing streams
● Marking positions in streams
● Skipping ahead in streams
● Finding the number of bytes in stream
● and many more
Some input stream methods
DataInputStream
readShort( ) readDouble( )
readInt( ) readLine( )
readLong( ) readChar( )
readFloat( ) readBoolean( )
readUTF( )
Reading from Keyboard 1. DataInputStream r=new
DataInputStream(System.in);
1. import java.io.*;
2. class G5{
3. public static void main(String args[])throws Exception{
4.
5. InputStreamReader r=new InputStreamReader(System.in);
6. BufferedReader br=new BufferedReader(r);
7.
8. System.out.println("Enter your name");
9. String name=br.readLine();
10. System.out.println("Welcome "+name);
11. }
Output:Enter your name
12. } Amit
Welcome Amit
Reading bytes from a file and display data
1. import java.io.FileReader;
2. public class FileReaderExample {
3. public static void main(String args[])throws Exception{
4. FileReader fr=new FileReader("D:\\testout.txt");
5. int i;
6. while((i=fr.read())!=-1)
7. System.out.print((char)i);
8. fr.close();
9. }
10. }
BYTE OUTPUT STREAM CLASSES
Hierarchy of OutputStream
Class Description
ByteArrayOutputStream This class implements an output stream in which the data is written into a byte array.
DataOutputStream A data output stream lets an application write primitive Java data types to an output stream in a
portable way.
FileOutputStream A file output stream is an output stream for writing data to a File or to a FileDescriptor.
ObjectOutputStream An ObjectOutputStream writes primitive data types and graphs of Java objects to an
OutputStream.
Use of class OutputStream
Methods of OutputStream class
Method Description
close() Closes this output stream and releases any system resources associated with this
stream.
flush() Flushes this output stream and forces any buffered output bytes to be written out.
write(byte[] b) Writes b.length bytes from the specified byte array to this output stream.
write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output
stream.
● Writing bytes
● Closing streams
● Flushing streams
● etc.
DataOutputStream
writeShort( ) writeDouble( )
writeInt( ) writeLine( )
writeLong( ) writeChar( )
writeFloat( ) WriteBoolean( )
writeUTF( )
Storing data into a File
1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }
Copying bytes from one file to another
import java.io.*;
class IOTest{
public void readFile(){
try {
//Creating FileInputStream object.
FileInputStream fis = new FileInputStream("F:\\New folder\\data1.txt");
int i;
//read file.
while((i=fis.read())!=-1){
fos.write(i);
}