Java通过标准输入流System.in实现命令行输入交互,支持Scanner或BufferedReader读取用户输入,最佳实践包括异常处理、资源关闭及输入验证,确保程序健壮性。
核心方法:Scanner类(推荐)
java.util.Scanner
是最简单的命令行输入工具,适合初学者和基础场景。
示例代码:
import java.util.Scanner; public class ScannerExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 创建Scanner对象 System.out.print("请输入姓名:"); String name = scanner.nextLine(); // 读取整行文本 System.out.print("请输入年龄:"); int age = scanner.nextInt(); // 读取整数 System.out.println(name + "的年龄是" + age + "岁"); scanner.close(); // 关闭资源 } }
关键方法:
nextLine()
:读取整行字符串(含空格)nextInt()
/nextDouble()
:读取整数/浮点数next()
:读取单个单词(空格分隔)hasNextInt()
:验证输入是否为整数(避免异常)
进阶方法:BufferedReader类
BufferedReader
配合 InputStreamReader
可高效处理大文本输入,需手动处理异常。
示例代码:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BufferedReaderExample { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { System.out.print("输入城市:"); String city = reader.readLine(); // 读取整行 System.out.print("输入温度:"); double temperature = Double.parseDouble(reader.readLine()); // 转换类型 System.out.println(city + "的温度是" + temperature + "℃"); } catch (IOException | NumberFormatException e) { System.err.println("输入错误: " + e.getMessage()); } } }
优势:
- 高性能:适合读取大量数据
- 灵活:
readLine()
统一获取字符串,可自定义解析逻辑
方法对比与选型建议
特性 | Scanner | BufferedReader |
---|---|---|
易用性 | ⭐⭐⭐⭐(自动解析类型) | ⭐⭐(需手动转换类型) |
性能 | ⭐⭐(较慢) | ⭐⭐⭐⭐(缓冲加速) |
异常处理 | 隐式捕获(需校验类型) | 显式处理IOException |
适用场景 | 简单交互、小数据量 | 大文件读取、高频输入 |
常见错误与避坑指南
-
输入类型不匹配
// 错误:输入非数字时崩溃 int num = scanner.nextInt(); // 正确:先验证再读取 if (scanner.hasNextInt()) { int num = scanner.nextInt(); } else { System.out.println("请输入数字!"); }
-
换行符残留问题
scanner.nextInt(); // 读取数字 scanner.nextLine(); // 必须消耗换行符 String text = scanner.nextLine(); // 再读字符串
-
资源未关闭
使用后调用scanner.close()
或reader.close()
释放系统资源(或使用try-with-resources)。
最佳实践总结
- 基础场景:优先用
Scanner
,简化类型转换。 - 性能敏感场景:选
BufferedReader
+ 手动解析。 - 安全提示:
- 始终验证输入内容(如数字范围、字符串格式)。
- 用
try-catch
处理异常(特别是BufferedReader
)。 - 避免混用
nextLine()
和其他nextXxx()
方法。
通过灵活运用这两种方法,可高效实现Java命令行交互功能,实际开发中,复杂场景可结合正则表达式或第三方库(如Apache Commons CLI)增强输入处理能力。
引用说明: 基于Oracle官方文档Java SE 17 Scanner与BufferedReader技术规范,并结合实际开发经验总结。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/6228.html