English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Until Java 1.5Before reading data from the user programmer, it depends on character stream classes and byte stream classes.
From Java 1.5The Scanner class is introduced. This class accepts File, InputStream, Path, and String objects, and reads all primitive data types and String tokens (from the given source) one by one using regular expressions.
By default, spaces are considered delimiters (used to split data into tokens).
Read various data types from the sourcenextXXX()
The methods provided by this class,nextInt()
,nextShort()
,nextFloat()
,nextLong()
,nextBigDecimal()
,nextBigInteger()
,nextLong()
,nextShort()
,nextDouble()
,nextByte()
,nextFloat()
,next()
.
You can pass a Scanner object as a parameter to a method.
The following Java program demonstrates how to pass a Scanner object to a method. The object reads the content of the file.
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; public class ScannerExample { public String sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); while(sc.hasNext()) { sb.append(sc.nextLine()); } return sb.toString(); } public static void main(String args[]) throws IOException { //Instantiate the inputStream class InputStream stream = new FileInputStream("D:\\sample.txt"); //Instantiate Scanner class Scanner sc = new Scanner(stream); ScannerExample obj = new ScannerExample(); //Call Method String result = obj.sampleMethod(sc); System.out.println("File content:"); System.out.println(result); } }
File Content: oldtoolbag.com originated from the idea that there exists a class of readers who respond better to on-line content and prefer to learn new skills at their own pace from the comfort of their drawing rooms.
In the following example, we create a Scanner object with standard input (System.in) as the source and pass it as a parameter to the method.
import java.io.IOException; import java.util.Scanner; public class ScannerExample { public void sampleMethod(Scanner sc){ StringBuffer sb = new StringBuffer(); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); String age = sc.next(); System.out.println("Hello "+name+" You are "+age+" years old"); } public static void main(String args[]) throws IOException { //Instantiate Scanner class Scanner sc = new Scanner(System.in); ScannerExample obj = new ScannerExample(); //Call Method obj.sampleMethod(sc); } }
Enter your name: Krishna Enter your age: 25 Hello Krishna You are 25 years old