Самый простой способ сделать это - использовать -D, поэтому, если у вас есть какой-то файл, вы можете вызвать
java -Dmy.file=file.txt javaprogram
А внутри вашей программы вы можете прочитать его с помощью System.getProperty("my.file")
.
public class Main {
public static void main(String[] args) {
String filename = System.getProperty("my.file");
if (filename == null) {
System.exit(-1); // Or wharever you want
}
// Read and process your file
}
}
Или вы можете использовать сторонний инструмент, такой как picocli
import java.io.File;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
@Command(name = "Sample", header = "%n@|green Sample demo|@")
public class Sample implements Runnable {
@Option(names = {"-f", "--file"}, required = true, description = "Filename")
private File file;
@Override
public void run() {
System.out.printf("Loading %s%n", file.getAbsolutePath());
}
public static void main(String[] args) {
CommandLine.run(new Sample(), System.err, args);
}
}