获取程序启动时的命令行参数
通过main方法的args数组直接获取程序启动时传入的参数:
public class StartupArgsExample {
public static void main(String[] args) {
// 示例:java StartupArgsExample file.txt --verbose
if (args.length > 0) {
System.out.println("参数列表:");
for (int i = 0; i < args.length; i++) {
System.out.println(i + ": " + args[i]);
}
} else {
System.out.println("未提供启动参数");
}
}
}
- 输出示例:
0: file.txt 1: --verbose - 注意事项:
- 参数以空格分隔,若参数含空格需用双引号包裹(如
"file name.txt")。 args[0]是第一个参数(非程序名)。
- 参数以空格分隔,若参数含空格需用双引号包裹(如
运行时获取用户输入
使用 Scanner 类(推荐简单场景)
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入用户名:");
String username = scanner.nextLine(); // 读取整行
System.out.print("请输入年龄:");
int age = scanner.nextInt(); // 读取整数
System.out.println("用户:" + username + ", 年龄:" + age);
scanner.close(); // 关闭资源
}
}
使用 BufferedReader(需处理IO异常)
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BufferedReaderExample {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("输入命令:");
String command = reader.readLine();
System.out.println("执行命令:" + command);
reader.close();
}
}
使用 Console 类(安全输入密码)
public class ConsoleExample {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("当前环境不支持Console");
return;
}
char[] password = console.readPassword("密码:"); // 输入不回显
console.printf("密码长度:%d\n", password.length);
}
}
- 适用场景对比:
| 方法 | 优点 | 缺点 |
|——————–|—————————–|————————–|
|Scanner| 简单易用,支持多种数据类型 | 不直接支持密码隐藏 |
|BufferedReader| 高效处理大文本 | 需手动转换数据类型 |
|Console| 支持密码隐藏,安全性高 | 在IDE中可能返回null|
获取系统属性参数(-D启动参数)
通过System.getProperty()获取-D传递的系统属性:
public class SystemPropertyExample {
public static void main(String[] args) {
// 启动命令:java -Dconfig.path="/etc/app.conf" SystemPropertyExample
String configPath = System.getProperty("config.path");
if (configPath != null) {
System.out.println("配置文件路径:" + configPath);
} else {
System.out.println("未指定配置路径");
}
}
}
关键注意事项
- 参数解析进阶:
- 复杂参数建议使用库如 Apache Commons CLI 或 Picocli。
- 输入验证:
- 对用户输入做校验(如空值、类型转换异常):
try { int num = Integer.parseInt(input); } catch (NumberFormatException e) { System.err.println("输入非数字!"); }
- 对用户输入做校验(如空值、类型转换异常):
- 资源释放:
Scanner和BufferedReader需调用close()释放资源(Java 7+可用try-with-resources)。
- 跨平台问题:
- 换行符:Windows用
\r\n,Linux/macOS用\n,Scanner和BufferedReader已自动处理。
- 换行符:Windows用
- 启动参数 → 用
main方法的args数组。 - 运行时输入 → 选
Scanner(基础交互)、BufferedReader(高性能)或Console(密码场景)。 - 系统属性 → 通过
System.getProperty()获取-D参数。
根据需求选择合适方法,并始终验证输入安全性,对于复杂命令行工具,推荐使用成熟的解析库提升效率。
引用说明:本文内容参考Oracle官方文档Java Console类、Scanner类及Java命令行参数规范。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/9403.html