Stream is nothing but sequence of bytes which makes input and output operations feasible and faster. It is called stream because it facilitates a continuous flow of data. An Input/Output stream is an input source or output destination which represents various types of sources. Java uses the concept of stream to make I/O operation fast. All the classes required for I/O operation are given in java.iopackage
In java, I/O is used to receive input data and produce output by processing the input provided.
Example for File Class:
package com.jbk.fileio;
import java.io.File;
import java.util.Date;
public class FileInfoExample {
public static void main(String[] args) {
File apath = new File("C:/test/abc.txt");
// Check if exists.
System.out.println("Path exists? "+ apath.exists());
if (apath.exists()) {
// Check if 'apath' is a directory.
System.out.println("Directory? "+ apath.isDirectory());
// Check 'apath' is a Hidden path.
System.out.println("Hidden? "+ apath.isHidden());
System.out.println("Simple Name: " + apath.getName());
System.out.println("Absolute Path: "+ apath.getAbsolutePath());
// Check file size (in bytes):
System.out.println("Length (bytes): " + apath.length());
// Last modify (in milli second)
long lastMofifyInMillis = apath.lastModified();
Date lastModifyDate = new Date(lastMofifyInMillis);
System.out.println("Last modify date: " + lastModifyDate);
}
}
}
There are two types of streams, which are Character Stream and Byte stream.
The Java platform stores character values using Unicode conventions. Character I/O stream automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.
For most applications, I/O with character stream is no more complicated than I/O with binary streams. Input and output done with stream classes automatically translates to and from the local character set.
A program that uses character stream in place of byte streams automatically adapts to the local character set and is ready for internationalisation - all without extra effort by the programmer.
All character stream classes are descended from Reader and Writer. As with byte streams, there are character stream classes that specialise in file I/O: FileReader and FileWriter.
Classes under this hierarchy are used for reading and writing characters from file, which are text files.
package com.javabykiram.IO;
Import java.io.Filewriter;
public class CopyCharacters {
public static void main(String[] args) throws Exception {
FileReader reader = null;
Filewriter writer = null;
try {
reader = new FileReader(“jbk.txt”);
writer = new FileWriter(“coralsoft.txt”); int c;
while ((c=reader.read()) !=-1){
writer.writer(c);
}
}finally{
if (reader !=null){ reader.close();
}
if (writer !=null){ writer.close();
}
}
}
Now, we have a lot of classes in this hierarchy of reader and writer. Every class has some more features. In the above example we copy characters by characters. For that we use BufferedReader and PrintWriter classes as shown below:
Programs use byte streams to perform input and output of 8-bytes. All byte stream classes are descended from InputStream and OutputStream classes.
There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, File Input Stream and File Output Stream. Other kind of byte streams are used much in the same way; the difference is mainly in the way they are constructed.
These classes are used for binary data. We can use these classes for text files as well.
Character streams are wrapper for binary streams. This means that the character stream uses the binary stream internally.
Java uses OutputStream and InputStream for Writing data to destination and Reading data from source, respectively.
OutputStream and InputStream are abstract classes. So we can't use them directly
Output Stream class: OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. Like FileOutputStream, ObjectOutputStream, etc.
Input Stream class: InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes, like File Input Stream, Object Input Stream, etc.
The abstract superclass InputStream declares an abstract method read() to read one data-byte from the input source.
The read() method :
Returns the input byte read as an int in the range of 0 to 255, or
Returns -1 if "end of stream" condition is detected, or
Throws an IOException if it encounters an I/O error
The read () method returns an int instead of a byte, because it uses -1 to indicate end-of- stream.
The read () method blocks until a byte is available, an I/O error occurs, or the "end-of- stream" is detected. The term "block" means that the method (and the program) will be suspended. The program will resume only when the method returns.
Similar to the InputStream, the abstract superclass OutputStream declares an abstract method write() to write a data-byte to the output sink.
write()
: Takes an int as the input parameter
The least-significant byte of the int argument is written out; the upper three bytes are discarded.
It throws an IOException if an I/O error occurs (for example, if output stream has been closed).
InputStream and OutputStream are abstract classes that cannot be instantiated. You need to choose an appropriate concrete subclass to establish a connection to a physical device. For example, you can instantiate a FileInputStream or FileOutputStream to establish a stream to a physical disk file.
We can use FileInputStream and FileOutputStream for File related operations
Example
How to Read File? [keep file in the d drive notes folder- write as a javabykiran.com in file]
package com;
import java.io.FileInputStream;
import java.io.IOException;
public class IOLab1 {
public static void main(String[] args){
try {
//windows file path - D:\notes\abc.txt //not allowed
//invalid escape sequence
String path = "D:\\notes\\abc.txt";
//or path = "D:/notes/abc.txt";
FileInputStream fis = new FileInputStream(path);
int i=0;
while((i=fis.read())!=-1){
char c =(char) i;
System.out.print(c);
}
fis.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
www.javabykiran.com
Example
How to Write to File?
package com;
import java.io.FileOutputStream; import java.io.IOException;
public class IOLab2 {
public static void main(String[] args) {
try {
//windows file path - D:\notes\abc.txt // not allowed
//Envalid escape sequence
String path = "D:\\notes\\abc.txt";
//or path = "D:/notes/abc.txt";
FileOutputStream fos = new FileOutputStream(path);
String s ="javabykiran Add- Karvenagar,pune";
byte b[] = s.getBytes();
fos.write(b);
System.out.println( "successfully written");
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Successfully written
Example
How to copy data from one file to another?
package com;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class IOLab3 {
public static void main(String[] args) {
try {
String srcpath = "D:\\WorkSpaces\\Eclipse_IndigoWS\\IO\\src\\com\\IOLab3.java";
String despath = "D:\\notes\\LabProgram3.txt";
FileInputStream fis = new FileInputStream(srcpath);
FileOutputStream fos = new FileOutputStream(despath);
int i=0;
while((i=fis.read())!=-1){
fos.write(i);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are some important classes that you would need to remember: BufferedInputStream and BufferedOutputStream
A BufferedInputStream adds functionality to another input stream, namely, the ability to buffer the input and to support the mark and reset methods.
When the BufferedInputStream is created, an internal buffer array is created. As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time.
The mark operation remembers a point in the input stream and the reset operation causes all the bytes read since the most recent mark operation to be reread before new bytes are taken from the contained input stream.
The BufferedOutput Stream implements a BufferedOutputStream. 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.
package com;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
public class IOLab5 {
public static void main(String[] args) {
try{
FileInputStream fin=new FileInputStream("D:\\notes\\abc.txt");
BufferedInputStream bufferedinputstream = new BufferedInputStream(fin);
int i=0;
while((i=bufferedinputstream.read())!=-1){
System.out.print((char)i);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
Output:
javabykiran Add- Karvenagar,pune
The file reader and file writer read and write information from text files.
These are the convenience classes for reading and writing character-oriented data.
So, it's good to avoid FileInputStream and FileOutputStream if you have to read and write the textual information.
The constructors of this classes assume that the default character encoding and the default byte-buffer size are appropriate.
For example: Copying data from one file to another file using FileReader and FileWriter.
package com;
import java.io.FileReader;
import java.io.IOException;
public class IOLab6 {
public static void main(String[] args) {
try {
String srcpath = " D:\\jbk\\IOLab6.java";
String des pat h = "D:\\notes\\LabProgram3.txt";
FileReader fr = new FileReader(srcpath);
FileWriter fw = new FileWriter(despath);
int i=0;
while((i=fr.read())!=-1){
fw.write(i);
System.out.print((char)i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are many ways to read from the keyboard. By using the following classes we can read the data from keyboard:
Example:
package com;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IOLab7 {
public static void main(String[] args) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inputStreamReader);
String name =" ";
while(true){
System.out.println("Enter Website :");
name = br.readLine(); //Reads a line of text
System.out.println("You Enter :"+name);
if(name.equals("www.javabykiran.com")){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Enter Website :
www.google.com
You Enter : www.google.com
Enter Website :
www.javabykiran.com
You Enter :www.javabykiran.com
Example:
Addition of two numbers by scanner class in 1.5 JDK:
package com;
import java.util.Scanner;
public class IOLab8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter 1st Number :");
int a = scanner.nextInt() ;
System.out.print("Enter 2st Number :");
int b = scanner.nextInt() ;
System.out.println("Addition is:"+(a+b));
}
}
Output:
Enter 1st Number :12
Enter 2st Number :20
Addition is :32
Example:
By using Console class
import java.io.Console;
class IOLab9 {
public static void main(String args[]){
Console c = System.console();
System.out.print("Enter the Name:");
String name = c.readLine();
System.out.print("Hello "+name);
}
}
Output:
Enter the Name : java
Hello java
This class can be used to read data from multiple streams.
A SequenceInputStream represents the logical concatenation of other input streams.
It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, where on it reads from the second one, and so on, until the end of file is reached on the last of the contained input streams.
Example:
Reading two files using SequenceInputStream –
package com;
import java.io.FileInputStream;
import java.io.SequenceInputStream;
public class IOLab10 {
public static void main(String[] args) {
try{
String path1 = "D:\\notes\\abc.txt";
String path2 = "D:\\notes\\xyz.txt";
FileInputStream fin1 = new FileInputStream(path1);
FileInputStream fin2 = new FileInputStream(path2);
SequenceInputStream sis = new SequenceInputStream(fin1,fin2);
int i =0;
while((i=sis.read())!=-1){
System.out.print((char)i);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
www.javabykiran.comCall us to join : 8888809416