【Java】Scanner 工具类全方位使用详解

哈喽各位小伙伴,Scanner 作为 Java 最常用的输入扫描工具,既能读取控制台键盘输入,也可以读取本地文件内容,还支持正则匹配查找,日常练手、小型项目接收用户输入基本离不开它。

一、Scanner 扫描控制台输入

Scanner 核心分为nextXxx()系列方法和nextLine(),二者换行处理逻辑差异很大,也是新手最容易踩坑的地方。

1. nextInt ()、next () 这类非整行读取方法

nextInt():读取控制台整数,遇到空格、回车、制表符就截止;如果输入非数字,直接抛出InputMismatchException

next():读取单个标记,以空白字符(空格、换行)作为分隔,无法读取带空格的完整字符串。

示例代码:

import java.util.Scanner;

public class ScannerTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一个整数:");
        int num = sc.nextInt();
        System.out.println("你输入的数字:" + num);

        System.out.print("请输入不带空格的字符串:");
        String str = sc.next();
        System.out.println("接收内容:" + str);
        sc.close();
    }
}

坑点提醒:nextInt()读取数字后,缓冲区会残留换行符\n,紧接着调用nextLine()会直接读到空字符串,后面会演示解决方案。

2. nextLine () 整行读取

nextLine():从当前游标位置一直读取到换行符\n为止,一次性接收一整行内容(包含空格),读取结束后游标自动跳到下一行开头,适合接收带空格的用户输入。

规避换行残留 bug 代码示例:

import java.util.Scanner;

public class NextLineDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("输入年龄:");
        int age = sc.nextInt();
        // 吃掉缓冲区遗留的换行,避免nextLine直接空读
        sc.nextLine();

        System.out.print("输入姓名(可带空格):");
        String name = sc.nextLine();
        System.out.println("姓名:" + name + ",年龄:" + age);
        sc.close();
    }
}

3. hasNext 系列判断方法

hasNext():判断是否还有下一个空白分隔的输入标记;

hasNextLine():判断输入流是否还有下一行数据;

日常循环读取不确定长度输入时经常搭配使用:

Scanner sc = new Scanner(System.in);
System.out.println("连续输入数字,输入非数字结束:");
while (sc.hasNextInt()){
    int temp = sc.nextInt();
    System.out.println("收到:"+temp);
}
sc.close();

除此之外还有nextDouble()hasNextDouble(),用来读取浮点型数据,用法和 nextInt 基本一致。

二、Scanner 扫描本地文件

Scanner 不止能绑定System.in控制台,还可以传入 File 对象实现文件内容读取,分逐行读取全内容读取两种场景。

1. 逐行读取文件内容

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

public class ReadFileByLine {
    public static void main(String[] args) {
        File file = new File("test.txt");
        try {
            Scanner sc = new Scanner(file);
            // 循环判断是否还有下一行
            while (sc.hasNextLine()){
                String line = sc.nextLine();
                System.out.println(line);
            }
            sc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件不存在!");
        }
    }
}

2. 读取整个文件内容

借助分隔符替换,把整个文件当做一个整体读取:

Scanner sc = new Scanner(new File("test.txt"));
// 将文件分隔符设置为空,一次性读取全部文本
sc.useDelimiter("\\Z");
String allContent = sc.next();
System.out.println(allContent);
sc.close();

注意:文件操作必须捕获文件不存在异常FileNotFoundException

三、Scanner 结合正则查找匹配内容

Scanner 内置findInLine()findWithinHorizon()两个方法,支持正则表达式,用来在字符串 / 文件中查找指定关键字,是简易文本检索的利器。

  • findInLine(String regex):在当前行中匹配正则,找到第一个符合内容就返回;
  • findWithinHorizon(String regex,int horizon):限定查找字符长度范围,全局匹配查找。

示例:在文本中查找所有数字

import java.util.Scanner;

public class FindWordDemo {
    public static void main(String[] args) {
        String content = "订单1001,金额299.9元,编号8856";
        Scanner sc = new Scanner(content);
        // 正则匹配数字
        String reg = "\\d+";
        String res;
        while ((res = sc.findInLine(reg)) != null){
            System.out.println("匹配数字:"+res);
        }
        sc.close();
    }
}

同样可以把数据源换成 File 文件,实现从文档中批量检索关键词,做简单日志筛选非常方便。

四、总结

  1. 控制台输入:需要整行带空格内容用nextLine(),单个数值 / 单词用nextInt/next,混用记得用空 nextLine 吃掉残留换行;
  2. 文件读取:Scanner 简化了 IO 读取代码,相比原生字符流写法更简洁,小文件读取首选;
  3. 正则检索:find 系列方法搭配正则,快速实现简易文本查找,不用手写复杂字符串截取;

Tags:

发表回复

Your email address will not be published. Required fields are marked *.

*
*