在Java中开发命令行工具可以通过多种方式实现,以下是几种常见的方法:
使用Java标准库
你可以使用Java标准库中的`java.lang.ProcessBuilder`类来执行外部命令行程序。
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CommandLineTool {
public static void main(String[] args) {
ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l");
try {
Process process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用Picocli框架
Picocli是一个功能强大且易于使用的Java命令行参数解析库,可以快速开发命令行工具。
```java
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParseException;
@Command(name = "ASCIIArt", mixinStandardHelpOptions = true, version = "ASCIIArt 1.0")
public class ASCIIArt implements Runnable {
@Option(names = {"-s", "--font-size"}, description = "Font size", defaultValue = "12")
private int fontSize;
@Override
public void run() {
System.out.println("Hello, World! Font size: " + fontSize);
}
public static void main(String[] args) {
CommandLine commandLine = new CommandLine(new ASCIIArt());
try {
commandLine.parseArgs(args);
} catch (ParseException e) {
System.err.println(e.getMessage());
commandLine.usage(System.err);
System.exit(1);
}
}
}
创建可执行的JAR文件
你可以将Java程序打包成可执行的JAR文件,通过`java -jar`命令运行。
```java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
编译并打包:
```sh
javac HelloWorld.java
jar cmf MANIFEST.MF HelloWorld.jar HelloWorld.class
运行:
```sh
java -jar HelloWorld.jar
命令行参数解析
Java中处理命令行参数可以通过以下方式:
```java
public class Cli {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
运行:
```sh
javac Cli.java
java Cli arg1 arg2 arg3
以上是Java开发命令行工具的一些基本方法。你可以根据具体需求选择合适的方法进行开发。如果你需要更复杂的命令行工具,Picocli框架提供了丰富的功能和选项,可以帮助你快速实现