Input and output in java

Input and Output (IO) are mainly used concepts in java real time applications to share objects from one place to another. Input represents data given to a program and output represents data displayed as a result of program. We are already familiar with the following two statements to display the output.

1
2
System.out.print();
System.out.println();

                Both of the statements are used to show the output on the screen. The difference between these two is that print() method keeps cursor in the same line after displaying the output and println() throws cursor to the next line after displaying the result.

Example to show the differences between print() and println() methods:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Sysout{
      public static void main(String[] args){
             int a,b;
             a = 10;
             b = 15;
             c = a+b;
             System.out.print("result of a+b is ");
             System.out.println(c)
      }
}

          There are two output print statements in the above program. First print statement will print 'result of a+b is' and cursor will be in same line only. So, when next print statement will get executed that will print the value of c in same line only, means the complete output will print in same line only.
          When it will get executes the println() method , out put will print and cursor move to next line.

Accepting input from the keyboard:
          A Stream is required to accept data from the keyboard. Stream represents the data flow from one place to other place. It is like water-pipe where water flows. A Stream is always required if we want to move data from one place to other place.

          Basically there are two types of streams one is input stream and another one is output stream. Input streams which receive or read data coming from some other place. Output streams are those streams which send or write data from other place.
            • System.in : This represents Input Stream object, which by default represents standard input device, i.e.keyboard.
            • System.out : This represents Print Stream object, which by default represents standard output device, i.e. monitor.
            • System.err : This field also represents Print Stream object, which by default represents monitor.
          * Connect the keyboard to an input stream object. Here, we can use InputStreamReader that can read data from keyboard.

1
InputStreamReader reader = new InputStreamReader(System.in);
         
          In this statement, we are creating InputStreamReader object and connecting the keyboard (System.in) to it.

         
* Connecting InputStreamReader to BufferedReader, which is another input type of stream. We are using BufferedReader as it has got methods to read data properly, coming from the stream.
1
BufferedReader br = new BufferedReader(reader);

          Here, we are creating BufferedReader object and connecting the InputStreamReader object to it.

Note: In the above two statements will combine and write in a single statement as,
1
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

          Now, we can read the data coming from the keyboard using read() and readLine() methods available in BufferedRerader class.
Accepting single character from the Keyboard:
          Follow these steps in order to accept single character from the keyboard.
              •  Create a BufferedReader class object(br).
              •  read a single character from the keyboard using read() method.

1
char ch = br.read();
         
          The above read() method it get ASCII number of the character in Integer format. That integer value can't save into character type variable char variable.

1
char ch = (char)br.read();
         
To accept and display a character from the keyboard:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.io.*;

class Accept{
     public static void main(String[] args)throws IOException{
          /*create BufferedReader object to accept data from the keyboard*/
          BufferedReader br = new BufferedReader(new  InputStreamReader(System.in));
          //Ask for character to read it
          System.out.print("Enter a character: ");
          char ch = (char)br.read();

          //Display the character
          System.out.println("You entered: "+ch);
     }
}

Accepting a String from keyboard:
          For reading a String from keyboard there is a readLine() method in BufferedReader class.

1
String str = br.readLine();
         
          The below one is the example to read a String from the keyboard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Import java.io.*;

public class Accept{
     public static void main(String[] args)throws IOException{
          /*Create BufferedReader object to accept data from keyboard*/
          BufferedReader br = new BufferedReader(new   InputStreamReader(System.in));

          //Ask for String and read it
          System.out.println("Enter a name: ");
          String name = br.readLine();
         
          //Display the String
          System.out.println("You entered: "+name);
     }
}

Accepting an Integer value from the keyboard:
          First we should accept the integer number from the keyboard as a String, using readLine().

1
String str = br.readLine();
         
          The number is in str in String format. That should be converted into int by using parseInt() method of Integer class.

1
int n = Integer.parseInt(str);

          The above two statements combined into a single statement.

1
int n = Integer.parseInt(br.readLine());
         
Here, is the example to read int value from the keyboard,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import java.io.*;

public class AcceptInt{
     public static void main(String[] args){
          /* Create BufferedReader object to read data from keyboard */
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          //Ask for integer and read it
          System.out.println("Enter an int value:");
          int num = Integer.parseInt(br.readLine());

          //display the int
          System.out.println("you entered:"+num);
     }
}

Reading input from Scanner:
          java.util.Scanner class will be helpful to read input from the keyboard or from a text file. When Scanner class loads input, that breakes into peaces called 'tokens'. These tokens can be retrieved from the Scanner object using the following methods.
            • next() - to read String
      • nextByte() - to read byte value
      • nextInt() - to read an Integer value
      • nextFloat() - to read float value
      • nextLong() - to read long value
      • nextDouble() - to read double value

          To read input from the keyboard we will use Scanner class as below

1
Scanner sc = new Scanner(System.in);

          If the user has given an integer value from the keyboard, it is stored into the Scanner object as a token. We can use the method sc.nextInt().
          Here is the program to read input from the keyboard.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javatbrains.io;

import java.util.Scanner;

public class ScannerKeyboard {
     public static void main(String[] args) {
          System.out.println("Enter id name sal:");
          Scanner sc = new Scanner(System.in);

          int id = sc.nextInt();
          String name = sc.next();
          float sal = sc.nextFloat();

          System.out.println("Id =  " + id);
          System.out.println("Name = " + name);
          System.out.println("Salary = " + sal);
     }
}
OutPut:
     Enter id name sal:
          12 JavaTBrains 1234.23  //passing input
          Id =  12
          Name = JavaTBrains
          Salary = 1234.23

          Here is the example to read text file using Scanner class. You need to create one text file with some content and pass that file path into File. This will read each and every line in the file and will print in console also as of the file format.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package com.javatbrains.io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerFile {
     public static void main(String[] args) throws FileNotFoundException {
          File file = new File("C:/<Your File Name>.txt");
          Scanner sc = new Scanner(file);

          int lineNumber = 1;
          while (sc.hasNextLine()) {
              String text = sc.nextLine();
              System.out.println(text);
              lineNumber++;
          }
     }
}

          If your passing input file is not present in the path, it will throws an exception called  FileNotFoundException.

Do you know?

Comments

Popular posts from this blog

how to count the page views by using JSP

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Multithreading in java with example