Likes

Input and Output in Java


Input and Output in Java
Input and Output (I/O) is used to process the input and produce the output based on the input. Java uses the concept of stream to make I/O operations fast. java.io package contains all the classes required for input and output operations.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it's like a stream of water that continues to flow.
Three streams are created for us automatically:
  • 1) System.out: standard output stream
  • 2) System.in: standard input stream
  • 3) System.err: standard error




OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source, it may be a file,an array,peripheral device or socket.




OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.
Commonly used methods of OutputStream class
Method
Description
1) public void write(int)throws IOException:
is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException:
is used to write an array of byte to the current output stream.
3) public void flush()throws IOException:
flushes the current output stream.
4) public void close()throws IOException:
is used to close the current output stream.




InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input stream of bytes.
Commonly used methods of InputStream class
Method
Description
1) public abstract int read()throws IOException:
reads the next byte of data from the input stream.It returns -1 at the end of file.
2) public int available()throws IOException:
returns an estimate of the number of bytes that can be read from the current input stream.
3) public void close()throws IOException:
is used to close the current input stream.



FileInputStream and FileOutputStream (File Handling):
FileInputStream and FileOutputStream classes are used to read and write data in file. In another words, they are used for file handling in java.



FileOutputStream class:
A FileOutputStream is an output stream for writing data to a file.
If you have to write primitive values then use FileOutputStream.Instead, for character-oriented data, prefer FileWriter.But you can write byte-oriented as well as character-oriented data.
Example of FileOutputStream class:
1.    //<b><i>Simple program of writing data into the file</i></b>  
2.      
3.      
import java.io.*; 
class Test{ 
  public static void main(String args[]){ 
   try{ 
     FileOutputStream fout=new FileOutputStream("abc.txt"); 
     String s="Sachin Tendulkar is my favourite player"; 
      
     byte b[]=s.getBytes(); 
     fout.write(b); 
      
     fout.close(); 

     System.out.println("success..."); 
    }catch(Exception e){System.out.println(e);} 
  } 
}  Output:success...




FileInputStream class:
A FileInputStream obtains input bytes from a file.It is used for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
It should be used to read byte-oriented data.For example, to read image etc.
Example of FileInputStream class:
1.    //<b><i>Simple program of reading data from the file</i></b>  
2.      
import java.io.*; 
class SimpleRead{ 
 public static void main(String args[]){ 
  try{ 
    FileInputStream fr=new FileInputStream("abc.txt"); 
    int i; 
    while((i=fr.read())!=-1) 
     System.out.print((char)i); 

    fr.close(); 
  }catch(Exception e){System.out.println(e);} 
 } 
}  Output:Sachin is my favourite player.




Example of Reading the data of current java file and writing it into another file
We can read the data of any file using the FileInputStream class whether it is java file, image file, video file etc. In this example, we are reading the data of C.java file and writing it into another file M.java.
import java.io.*;  
  
class C{  
public static void main(String args[])throws Exception{  
  
FileInputStream fin=new FileInputStream("C.java");  
FileOutputStream fout=new FileOutputStream("M.java");  
  
int i=0;  
while((i=fin.read())!=-1){  
fout.write((byte)i);  
}  
  
fin.close();  
}  
}  



FileWriter class:
FileWriter class is used to write character-oriented data to the file. Sun Microsystem has suggested not to use the FileInputStream and FileOutputStream classes if you have to read and write the textual information.
Example of FileWriter class:
In this example, we are writing the data in the file abc.txt.
import java.io.*;  
class Simple{  
 public static void main(String args[]){  
  try{  
   FileWriter fw=new FileWriter("abc.txt");  
   fw.write("my name is sachin");  
   fw.flush();  
  
   fw.close();  
  }catch(Exception e){System.out.println(e);}  
  System.out.println("success");  
 }  
}  
Output:success...



FileReader class:
FileReader class is used to read data from the file.
Example of FileReader class:
In this example, we are reading the data from the file abc.txt file.
import java.io.*;  
class Simple{  
 public static void main(String args[])throws Exception{  
  
  FileReader fr=new FileReader("abc.txt");  
  int i;             
  while((i=fr.read())!=-1)  
  System.out.println((char)i);  
  
  fr.close();  
 }  
}  
Output:my name is sachin


Reading data from keyboard:
There are many ways to read data from the keyboard. For example:
  • InputStreamReader
  • Scanner
InputStreamReader class:
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
  • connects to input stream of keyboard
  • converts the byte-oriented stream into character-oriented stream
BufferedReader class:
BufferedReader class can be used to read data line by line by readLine() method.
Example of reading data from keyboard by InputStreamReader and BufferdReader class:
In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard.
1.    //<b><i>Program of reading data</i></b>  
2.      
import java.io.*;  
class G5{  
public static void main(String args[])throws Exception{  
  
InputStreamReader r=new InputStreamReader(System.in);  
BufferedReader br=new BufferedReader(r);  
  
System.out.println("Enter your name");  
String name=br.readLine();  
System.out.println("Welcome "+name);  
 }  
}  
Output:Enter your name
       Amit
       Welcome Amit




Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop
In this example, we are reading and printing the data until the user prints stop.
import java.io.*;  
class G5{  
public static void main(String args[])throws Exception{  
  
 InputStreamReader r=new InputStreamReader(System.in);  
 BufferedReader br=new BufferedReader(r);  
  
 String name="";  
  
  while(!name.equals("stop")){  
   System.out.println("Enter data: ");  
   name=br.readLine();  
   System.out.println("data is: "+name);  
  }  
  
 br.close();  
 r.close();  
 }  
}  
Output:Enter data: Amit
       data is: Amit
       Enter data: 10
       data is: 10
       Enter data: stop
       data is: stop


java.util.Scanner class:
There are various ways to read input from the keyboard, the java.util.Scanner class is one of them. The Scanner class breaks the input into tokens using a delimiter which is whitespace bydefault. It provides many methods to read and parse various primitive values.
Commonly used methods of Scanner class:
There is a list of commonly used Scanner class methods:
  • public String next(): it returns the next token from the scanner.
  • public String nextLine(): it moves the scanner position to the next line and returns the value as a string.
  • public byte nextByte(): it scans the next token as a byte.
  • public short nextShort(): it scans the next token as a short value.
  • public int nextInt(): it scans the next token as an int value.
  • public long nextLong(): it scans the next token as a long value.
  • public float nextFloat(): it scans the next token as a float value.
  • public double nextDouble(): it scans the next token as a double value.
Example of java.util.Scanner class:
Let's see the simple example of the Scanner class which reads the int, string and double value as an input:
import java.util.Scanner;  
class ScannerTest{  
 public static void main(String args[]){  
  
   Scanner sc=new Scanner(System.in);  
     
   System.out.println("Enter your rollno");  
   int rollno=sc.nextInt();  
   System.out.println("Enter your name");  
   String name=sc.next();  
   System.out.println("Enter your fee");  
   double fee=sc.nextDouble();  
  
   System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);  
      
 }  
}   

Output:Enter your rollno
       111
       Enter your name
       Ratan
       Enter
       450000

       Rollno:111 name:Ratan fee:450000

No comments: