在java项目中有时需要依次(或循环,或单次)调用shell脚本文件,以便实现相应的功能,我们需要保证在执行shell文件命令时,能实现相关的功能。具体的做法是,在给定的某个类中定义一个static main方法,然后main方法根据输入的参数(来自命令行),决定执行相应的操作。如下:
public class classA{
//如下定义了CommandLineParse 对命令进行解析
private static final CommandLineParser parser = new PosixParser();
//首先定义了一个static main方法,它接收String[]数组参数
public static void main(String[] args) {
//在main方法中生成Options
CommandLine commandline = null;
try {
commandline = parseArgs(opts, args); //根据args,将输入的参数经Options解析到CommandLine中
} catch (ParseException e) {
printHelper(ClassA.class.getSimpleName(), opts); //一些其他的基本操作,在此不解释
return;
}
String beanName = commandline.getOptionValue('b');
ClassA classA = new ClassA(beanName);
System.exit(classA.execute()); //在这里调用execute方法
}
private static Options getOptions() {
Options opts = new Options();
opts.addOption(buildOption("b", "beanName", true, "bean in xml with configure", true));
opts.addOption("h", "help", false, "print help");
return opts;
}
private CommandLine parseArgs(Options options, String []args) throws ParseException{
return parser.parse(options, args);
}
public void execute(){
//使用execute方法,去执行所需要的命令
......................................................
}