欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA Scanner 类  

程序员文章站 2022-06-10 08:50:10
...

Scanner 是一个新的操作类,是在java.util 包中提供的一个操作类,使用此类可以方便的完成输入流的输入操作:


package org.scannerdemo;

import java.util.Scanner;

public class ScannerDemo01 {

	/**
	 * @param args
	 */
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		
		int i =0;
		
		if (scan.hasNextInt()){
			i = scan.nextInt();
		}
		
		System.out.println("i:=" +i);
		
		
		
	}

}

package org.scannerdemo;

import java.util.Scanner;

public class ScannerDemo02 {

	/**
	 * @param args
	 */
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		
		String str = "";
		
		if (scan.hasNext()){
			str = scan.next();
		}
		
		System.out.println("str:=" +str);
	}

}

支持正则匹配:


package org.scannerdemo;

import java.util.Scanner;

public class ScannerDemo04 {

	/**
	 * @param args
	 */
	@SuppressWarnings("resource")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scan = new Scanner(System.in);
		
		String str = "";
		
		if (scan.hasNext("\\d{4}-\\d{2}-\\d{2}")){
			str = scan.next();
		}
		
		System.out.println("str:=" +str);
	}

}



支持 InputSteam:


package org.scannerdemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerDemo03 {

	/**
	 * @param args
	 * @throws FileNotFoundException 
	 */
	@SuppressWarnings("resource")
	public static void main(String[] args) throws FileNotFoundException {
		// TODO Auto-generated method stub
		File file = new File ("d:\\1.txt");
		
		Scanner scan = new Scanner(new FileInputStream(file));
		
		scan.useDelimiter("\n");
		
		StringBuffer buf = new StringBuffer();
		
		while (scan.hasNext()){
			buf.append(scan.next()).append("\n");
		}
		
		System.out.println(buf);
	}

}