本文目录导读:

我来为你提供一个完整的Java命令行工具实现案例,包含多个实用功能示例。
基础命令行参数解析工具
import java.util.HashMap;
import java.util.Map;
public class CommandLineParser {
private Map<String, String> options = new HashMap<>();
private Map<String, String> longOptions = new HashMap<>();
public static void main(String[] args) {
CommandLineParser parser = new CommandLineParser();
try {
parser.parse(args);
parser.showHelp();
if (parser.hasOption("v")) {
System.out.println("版本: 1.0.0");
}
if (parser.hasOption("n")) {
System.out.println("名称: " + parser.getOptionValue("n"));
}
} catch (Exception e) {
System.err.println("错误: " + e.getMessage());
System.exit(1);
}
}
public void parse(String[] args) throws Exception {
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--")) {
// 长选项
String key = arg.substring(2);
if (i + 1 < args.length && !args[i + 1].startsWith("-")) {
longOptions.put(key, args[++i]);
} else {
longOptions.put(key, "true");
}
} else if (arg.startsWith("-")) {
// 短选项
String key = arg.substring(1);
if (i + 1 < args.length && !args[i + 1].startsWith("-")) {
options.put(key, args[++i]);
} else {
options.put(key, "true");
}
} else {
throw new Exception("无效的参数: " + arg);
}
}
}
public boolean hasOption(String key) {
return options.containsKey(key) || longOptions.containsKey(key);
}
public String getOptionValue(String key) {
return options.getOrDefault(key, longOptions.get(key));
}
private void showHelp() {
System.out.println("用法: java CommandLineParser [选项]");
System.out.println("选项:");
System.out.println(" -v, --version 显示版本号");
System.out.println(" -n, --name <名称> 指定名称");
System.out.println(" -h, --help 显示帮助信息");
System.out.println();
}
}
文件操作命令行工具
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
public class FileTool {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("用法: java FileTool [命令] [参数]");
System.out.println("命令:");
System.out.println(" list <目录> 列出文件");
System.out.println(" copy <源> <目标> 复制文件");
System.out.println(" delete <文件> 删除文件");
System.out.println(" move <源> <目标> 移动文件");
System.out.println(" size <文件> 显示文件大小");
return;
}
String command = args[0];
try {
switch (command) {
case "list":
listFiles(args[1]);
break;
case "copy":
copyFile(args[1], args[2]);
break;
case "delete":
deleteFile(args[1]);
break;
case "move":
moveFile(args[1], args[2]);
break;
case "size":
showFileSize(args[1]);
break;
default:
System.err.println("未知命令: " + command);
System.exit(1);
}
} catch (Exception e) {
System.err.println("错误: " + e.getMessage());
System.exit(1);
}
}
private static void listFiles(String dir) throws IOException {
Path path = Paths.get(dir);
if (!Files.exists(path)) {
throw new IOException("目录不存在: " + dir);
}
System.out.println("目录内容: " + dir);
System.out.println("----------------------");
try (Stream<Path> stream = Files.list(path)) {
stream.forEach(p -> {
try {
String type = Files.isDirectory(p) ? "[DIR]" : "[FILE]";
long size = Files.size(p);
System.out.printf("%-8s %-30s %10d bytes%n",
type, p.getFileName(), size);
} catch (IOException e) {
System.err.println("无法读取: " + p);
}
});
}
}
private static void copyFile(String src, String dest) throws IOException {
Path source = Paths.get(src);
Path target = Paths.get(dest);
if (!Files.exists(source)) {
throw new IOException("源文件不存在: " + src);
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件复制成功: " + src + " -> " + dest);
}
private static void deleteFile(String file) throws IOException {
Path path = Paths.get(file);
if (!Files.exists(path)) {
throw new IOException("文件不存在: " + file);
}
Files.delete(path);
System.out.println("文件删除成功: " + file);
}
private static void moveFile(String src, String dest) throws IOException {
Path source = Paths.get(src);
Path target = Paths.get(dest);
if (!Files.exists(source)) {
throw new IOException("源文件不存在: " + src);
}
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件移动成功: " + src + " -> " + dest);
}
private static void showFileSize(String file) throws IOException {
Path path = Paths.get(file);
if (!Files.exists(path)) {
throw new IOException("文件不存在: " + file);
}
long size = Files.size(path);
System.out.printf("文件: %s%n大小: %d bytes (%.2f KB, %.2f MB)%n",
file, size, size / 1024.0, size / (1024.0 * 1024.0));
}
}
交互式命令行工具
import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
public class InteractiveCLI {
private static Scanner scanner = new Scanner(System.in);
private static Map<String, String> data = new HashMap<>();
public static void main(String[] args) {
System.out.println("交互式命令行工具");
System.out.println("输入 'help' 查看命令列表");
while (true) {
System.out.print(">>> ");
String input = scanner.nextLine().trim();
if (input.isEmpty()) {
continue;
}
if (input.equals("exit") || input.equals("quit")) {
System.out.println("再见!");
break;
}
processCommand(input);
}
}
private static void processCommand(String input) {
String[] parts = input.split("\\s+");
String command = parts[0].toLowerCase();
switch (command) {
case "help":
showHelp();
break;
case "add":
if (parts.length == 3) {
data.put(parts[1], parts[2]);
System.out.println("添加成功: " + parts[1] + " -> " + parts[2]);
} else {
System.out.println("用法: add <键> <值>");
}
break;
case "get":
if (parts.length == 2) {
String value = data.get(parts[1]);
System.out.println(value != null ? value : "键不存在: " + parts[1]);
} else {
System.out.println("用法: get <键>");
}
break;
case "list":
if (data.isEmpty()) {
System.out.println("暂无数据");
} else {
data.forEach((k, v) -> System.out.println(k + " = " + v));
}
break;
case "delete":
if (parts.length == 2) {
String removed = data.remove(parts[1]);
System.out.println(removed != null ?
"删除成功: " + parts[1] : "键不存在: " + parts[1]);
} else {
System.out.println("用法: delete <键>");
}
break;
case "clear":
data.clear();
System.out.println("数据已清空");
break;
case "count":
System.out.println("数据条目数: " + data.size());
break;
default:
System.out.println("未知命令: " + command);
showHelp();
}
}
private static void showHelp() {
System.out.println("可用命令:");
System.out.println(" add <键> <值> 添加/更新数据");
System.out.println(" get <键> 获取数据");
System.out.println(" list 列出所有数据");
System.out.println(" delete <键> 删除数据");
System.out.println(" clear 清空所有数据");
System.out.println(" count 显示数据数量");
System.out.println(" help 显示帮助");
System.out.println(" exit/quit 退出程序");
}
}
进度显示工具类
import java.text.SimpleDateFormat;
import java.util.Date;
public class ProgressBar {
public static void main(String[] args) {
// 示例:模拟进度条
System.out.println("进度显示示例:");
for (int i = 0; i <= 100; i += 10) {
showProgress(i, 100, "任务进行中");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("\n完成!");
}
public static void showProgress(int current, int total, String message) {
int barLength = 50;
int percent = (int) ((current / (double) total) * 100);
int filledLength = (int) (barLength * current / (double) total);
StringBuilder bar = new StringBuilder();
for (int i = 0; i < barLength; i++) {
if (i < filledLength) {
bar.append("█");
} else {
bar.append("░");
}
}
String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
System.out.printf("\r[%s] %s %3d%% | %s",
time, bar.toString(), percent, message);
System.out.flush();
}
}
彩色输出工具类
public class ColorOutput {
// ANSI颜色代码
public static final String RESET = "\u001B[0m";
public static final String BLACK = "\u001B[30m";
public static final String RED = "\u001B[31m";
public static final String GREEN = "\u001B[32m";
public static final String YELLOW = "\u001B[33m";
public static final String BLUE = "\u001B[34m";
public static final String PURPLE = "\u001B[35m";
public static final String CYAN = "\u001B[36m";
public static final String WHITE = "\u001B[37m";
public static void main(String[] args) {
printColoredExample();
}
public static void printColoredExample() {
System.out.println("彩色输出示例:");
System.out.println(RED + "这是红色" + RESET);
System.out.println(GREEN + "这是绿色" + RESET);
System.out.println(YELLOW + "这是黄色" + RESET);
System.out.println(BLUE + "这是蓝色" + RESET);
System.out.println(PURPLE + "这是紫色" + RESET);
System.out.println(CYAN + "这是青色" + RESET);
// 背景色
System.out.println("\u001B[41m" + "红底白字" + RESET);
System.out.println("\u001B[42m" + "绿底黑字" + RESET);
}
}
编译和运行方法
# 编译 javac CommandLineParser.java javac FileTool.java javac InteractiveCLI.java javac ProgressBar.java javac ColorOutput.java # 运行示例 java CommandLineParser -n "Test" -v java FileTool list . java InteractiveCLI java ProgressBar java ColorOutput # 带更多参数的文件操作工具示例 java FileTool list /tmp java FileTool copy source.txt dest.txt
使用示例
-
命令行解析器:
java CommandLineParser -v -n "Hello" # 输出: # 版本: 1.0.0 # 名称: Hello
-
文件工具:
java FileTool list /home/user # 输出: /home/user # [DIR] documents 1024 bytes # [FILE] test.txt 5120 bytes
这些工具类提供了命令行应用开发的基础框架,你可以根据需求扩展和组合使用,每个工具都有明确的职责划分和易用的API设计,适合作为命令行项目的起点。