English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
까지 Java 1.5사용자 프로그래머로부터 데이터를 읽기 전까지, 모두 문자流向字节流向에 의존합니다.
Java에서 1.5Scanner 클래스를 시작합니다. 이 클래스는 File, InputStream, Path 및 String 객체를 받아들여 정규 표현식을 사용하여 모든 원시 데이터 타입과 String 토큰을 하나씩 읽습니다(지정된 원본에서).
기본적으로, 공백은 구분자로 간주됩니다(데이터를 토큰으로 나눕니다).
원본에서 다양한 데이터 타입을 읽습니다.nextXXX()
이 클래스는 제공하는 메서드를 통해nextInt()
,nextShort()
,nextFloat()
,nextLong()
,nextBigDecimal()
,nextBigInteger()
,nextLong()
,nextShort()
,nextDouble()
,nextByte()
,nextFloat()
,next()
.
Scanner 객체를 메서드에 전달할 수 있습니다.
다음 Java 프로그램은 Scanner 객체를 메서드에 전달하는 방법을 보여줍니다. 이 객체는 파일의 내용을 읽습니다.
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 { //inputStream 클래스를 인스턴스화합니다. InputStream stream = new FileInputStream("D:\\sample.txt"); //Scanner 클래스를 인스턴스화 Scanner sc = new Scanner(stream); ScannerExample obj = new ScannerExample(); //메서드 호출 String result = obj.sampleMethod(sc); System.out.println("파일 내용:"); System.out.println(result); } }
파일 내용: oldtoolbag.com is 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 comforts of their drawing rooms.
아래의 예제에서는 표준 입력(System.in)을 소스로 가진 Scanner 객체를 생성하고 그 값을 메서드에 전달합니다.
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 { //Scanner 클래스를 인스턴스화 Scanner sc = new Scanner(System.in); ScannerExample obj = new ScannerExample(); //메서드 호출 obj.sampleMethod(sc); } }
Enter your name: Krishna Enter your age: 25 Hello Krishna You are 25 years old