Java Notes Unit VI
Java Notes Unit VI
Java performs I/O through Streams. A Stream is linked to a physical layer by java
I/O system to make input and output operation in java. A stream can be defined as
a sequence of data. The InputStream is used to read data from a source and the
OutputStream is used for writing data to a destination. InputStream and
OutputStream are the basic stream classes in Java.
Types of streams:
• Byte Stream : It provides a convenient means for handling input and output
of byte.
• Character Stream : It provides a convenient means for handling input and
output of characters. Character stream uses Unicode and therefore can be
internationalized.
1. Byte Stream:
Byte Stream Classes are used to read bytes from an input stream and write bytes to
an output stream.
Character stream is also defined by using two abstract classes at the top of the
hierarchy, they are Reader and Writer. These two abstract classes have several
concrete classes that handle Unicode characters.
• Reader classes : Abstract class that define character stream input.
• Writer classes : Abstract class that define character stream output.
Example:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedInputStreamExample {
public static void main(String args[]) throws IOException {
//Creating an BufferedInputStream object
BufferedInputStream inputStream = new BufferedInputStream(System.in);
byte bytes[] = new byte[1024];
System.out.println("Enter your data ");
//Reading data from key-board
inputStream.read(bytes);
//Creating BufferedOutputStream object
FileOutputStream out= new FileOutputStream("D:/sample.txt");// writer file
BufferedOutputStream outputStream = new BufferedOutputStream(out);
//Writing data to the file
outputStream.write(bytes);
outputStream.flush();
System.out.println("Data successfully written in the specified file");
}
}
Example:
To create a file in Java, you can use the createNewFile() method. This method
returns a boolean value true if the file was successfully created, and false if the file
already exists. It is necessary to enclose method in try...catch block because it
throws an IOException if an error occurs (if the file cannot be created for some
reason).
Example:
The FileWriter class together with its write() method to write some text to the file
we created. Note that when you are done writing to the file, you should close it
with the close() method.
Example:
3. Reading Files:
The Scanner class is used to read the contents of the file we created in java.
Creating object for Scanner class to fetch and read the file contents.
Example:
In File class delete() method is used to delete the created file in java. The object for
File class is created to delete the file in java.
Example: