카테고리 없음

[Java] command line argument 파싱

잘할수있을거야 2022. 9. 7. 15:49
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class CshMain {

	public static void main(String[] args) {
		try {

			Options options = new Options();
			options.addOption(Option.builder().option("t").longOpt("test").hasArg().required().build());

			options.addOption(Option.builder().option("t2").longOpt("test2").required().build());

			CommandLineParser parser = new DefaultParser();

			CommandLine cmd = parser.parse(options, args);

			System.out.println("t 옵션 값");
			String str = cmd.getOptionValue("t");
			if (str == null) {
				System.out.println("str is null");
			} else if (str.equals("")) {
				System.out.println("str is empty");
			} else {
				System.out.println(str);
			}

			System.out.println();

			System.out.println("t2 옵션 값");
			String str2 = cmd.getOptionValue("t2");
			if (str2 == null) {
				System.out.println("str2 is null");
			} else if (str2.equals("")) {
				System.out.println("str2 is empty");
			} else {
				System.out.println(str2);
			}

		} catch (MissingOptionException missingException) {
			missingException.printStackTrace();
			List list = missingException.getMissingOptions();
			for (int i = 0; i < list.size(); i++) {
				System.out.println(list.get(i));
			}
		} catch (ParseException parseException) {
			parseException.printStackTrace();
		}

	}

}