Monday 14 November 2016

JAVA INPUT/OUTPUT



I/O Basics:
    Java provides strong, flexible support for I/O as it relates to files and networks.
    Java’s I/O system is cohesive and consistent.
    Streams:
o   Java program performs I/O through streams.
o   A stream is an abstraction that either produces or consumes information.
o   A stream is linked to a physical device by the Java I/O system.
o   All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to any type of devices.
o   An input stream can abstract many types of input: from a disk file, a keyboard, or a network connection.
o   An output stream may refer to a console, a disk file, or a network connection.
o   Java implements streams within class hierarchies defined in the java.io package.
Byte and Character Streams:
 Java defines two types of streams:byte and character.
 Bytestream provides a convenient means for handling input and output of bytes.
 Byte streams are used when reading or writing binary data.
 Character stream provides a convenient means for handling input and output ofcharacters.
 At the lowest level, all I/O is still byte oriented.
 The character-based streams simply provide a convenient and efficient means for handling characters.

The Byte Stream Classes:
o   Byte streams are defined by using two class hierarchies. At the top are two abstract classes:InputStream and OutputStream.
o   The abstract classes InputStream and OutputStreamdefine several key methods that the other stream classes implement. Two of the most important areread() and write(), which, respectively, reads and write bytes of data.
o   Byte stream classes are shown below:
Stream Classes
Meaning
BufferedInputStream
Buffered Input Stream
BufferedOutputStream
Buffered Output Stream
ByteArrayInputStream
Input stream that reads from a byte array
ByteArrayOutputStream
Output stream that writes to a byte array
DataInputStream
An input stream that contains methods for reading the Java’s standard data types.
DataOutputStream
An output stream that contains methods for writing the Java’s standard data types.
FileInputStream
Input stream that reads from a file.
FileOutputStream
Output stream that writes to a file.
FilterInputStream
Implements InputStream.
FilterOutputStream
Implements OutputStream.
InputStream
Abstract class that describes stream input.
ObjectInputStream
Input Stream for objects.
ObjectOutputStream
Output Stream for objects.
OutputStream
Abstract class that describes stream output.
PipedInputStream
Input pipe
PipedOutputStream
Output pipe
PrintStream
Output stream that contains print() and println()
PushbackInputStream
Input byte that supports one-byte “unget,” which returns a byte to the input stream.
RandomAccessFile
Supports random access file I/O
SequenceInputStream
Input stream that is a combination of two or more input streams that will be read sequentially, one after the other.

The Character Stream Classes:
o   Character streams are defined by using two class hierarchies. At the top are two abstract classes: Reader and Writer.
o   These abstract classes handle Unicode character stream.
o   The abstract classes Reader and Writerdefine several key methods that the other stream classes implement. Two of the most important are read() and write(), which, respectively, reads and write characters of data. These methods are overridden by derived stream classes.
o   Character stream classes are shown below:
Stream Classes
Meaning
BufferedReader
Buffered Input Character Stream
BufferedWriter
Buffered Output Character Stream
CharArrayReader
Input stream that reads from a Character array
CharArrayWriter
Output stream that writes to a Character array
FileReader
Input stream that reads from a file.
FileWriter
Output stream that writes to a file.
FilterReader
Filtered reader
FilterWriter
Filtered writer
InputStreamReader
Input stream that translates bytes to characters.
LineNumberReader
Input stream that counts lines.
OutputStreamWriter
Output stream that translates bytes to characters.
PipedReader
Input pipe
PipedWriter
Output pipe
PrintWriter
Output stream that contains print() and println()
PushbackReader
Input stream that allow characters to be returned to the input stream.
Reader
Abstract class that describes character stream input.
StringReader
Input stream that reads from a string.
StringWriter
Output stream that writes to a string.
Writer
Abstract class that describes character stream output.

Working with FileInputStream:
 FileInputStream class creates an InputStreamthat can be used to read bytes from a file.
 Its two most common constructors are:
FileInputStream(String filepath)
FileInputStream(File fileObj)
filepath is the full path name of a file, and fileObj is a File object that describes the file.
They can throw FileNotFoundException.
 The following example creates two FileInputStream that uses the same disk file:
FileInputStream f1=new FileInputStream(“/myfile.txt”);
File f=new File(“/myfile.txt”);
FileInputStream f1=new FileInputStream(f);
 The various methods that of the abstract class InputStreamthat FileInputStream overrides are:
Method
Description
int available()
Returns the number of bytes of input currently available for reading.
void close()
Close the input source.
booleanmarkSupported()
Returns true if mark()/reset() are supported by the invoking stream
int read()
Returns an integer representation of the next available byte of input. -1 is returned at End of file.
int read(byte buffer[])
Attempts to read up to buffer.length bytes into buffer and return the actual number of bytes successfully read. -1 is returned at End of file.
int read(byte buffer[], int offset, intnumBytes)
Attempts to read up to numBytes bytes into the buffer starting at buffer[offset], return the number of bytes successfully read. -1 is returned at End of file.
long skip(long numBytes)
Ignores or skips numBytes bytes of input, returning the number of bytes actually ignored.

 Example:
import java.io.*;
classFileinput{
public static void main(String args[]) {
try{
InputStream f=new FileInputStream("Finally.java");
System.out.println("\nTotal Size Of Finally.java is:"+f.available()+" bytes");
}
catch(Exception e){}
 }
}
Output:
Total Size Of Finally.java is: 337 bytes
Working with FileOutputStream:
 FileOutputStream class creates an OutputStreamthat can be used to write bytes toa file.
 Its most common constructors are:
FileOutputStream(String filepath)
FileOutputStream(File fileObj)
FileOutputStream(String filepath,boolean append)
FileOutputStream(File fileObj, boolean append)
They can throw FileNotFoundException.
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 FileOutputStream is not dependent on the File already existing.FileOutputStreamwill create the file before opening it for output.
 In case of opening a read only file, an IOException will be thrown.
 Example:
import java.io.*;
classFileoutput{
public static void main(String args[]) {
  String s="This program writes a code into a file name MyFile.txt and store it";
try {
FileOutputStream f2=new FileOutputStream("File2.txt");
byte b[]=s.getBytes();
f2.write(b);
f2.close();
System.out.println("\nFile2 Written Successfully");
  }
catch(Exception e){}
 }
}
Output:
File2 Written Successfully
Working with PrintStream:
 PrintStreamclass provides all the output capabilities that can be used from the System file handle.
 It implements the Appendable, Closeable,and Flushable interfaces.
 PrintStream defines several constructor:
PrintStream(OutputStreamoutputStream)
PrintStream(OutputStreamoutputStream, booleanflushOnNewline)
PrintStream(OutputStreamoutputStream, booleanflushOnNewline, String charSet)
Here, outputStream specifies an openOutputStream that will receive output. The flushOnNewline 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.
 The next set of constructors gives an easy way to construct a PrintStreamthat write its output to a file:

PrintStream(File outputFile) throws FileNotFoundException
PrintStream(File outputFile, String charSet) throws FileNotFoundException , UnsupportedEncodingException
PrintStream(String outputFileName) throws FileNotFoundException
PrintStream(String outputFileName, String charSet) throws FileNotFoundException, UnsupportedEncodingException

These allow a PrintStream to be created from a Fileobject or by specifying the name of a file.
It is also possible to specify character encoding by passing its name in charSet.
 PrintStreamsupports the print() and println() methods for all types, including objects.
 Example:
import java.io.*;
classPrintstream
{
public static void main(String args[]) throws FileNotFoundException
 {
PrintStream p=new PrintStream("File1.txt");
p.println("Hello this is written to the file using print stream");
p.println("Again the next line is also written to the file");
System.out.println("\nData is successfully written to the file");
 }
}
Output:
Data is successfully written to the file

No comments:
Write comments