1 package jimm.util; 2 import java.util.HashMap ; 3 4 15 public class Getopts { 16 String [] argv; 17 HashMap options = new HashMap (); 18 boolean errorFlag = false; 19 20 30 public Getopts(String optionListString, String [] args) { 31 String optChoices = optionListString; 32 33 for (int index = 0; index < args.length; ++index) { 34 String arg = args[index]; 35 if (arg.startsWith("-")) { 36 char optionChar = arg.charAt(1); 37 int optionLoc = optChoices.indexOf(optionChar); 38 if (optionLoc == -1) 39 errorFlag = true; 40 else { 41 boolean hasArgument = 43 optChoices.length() > optionLoc + 1 && 44 optChoices.charAt(optionLoc + 1) == ':'; 45 if (hasArgument) { 46 String optarg = arg.substring(2); 47 if (optarg.equals("")) { 48 ++index; 49 try { 50 optarg = args[index]; 51 } 52 catch (Exception e) { optarg = ""; 54 errorFlag = true; 55 } 56 } 57 options.put(new Character (optionChar), optarg); 58 } 59 else { 60 options.put(new Character (optionChar), ""); 62 } 63 } 64 } 65 else { argv = new String [args.length - index]; 67 int offset = index; 68 while (index < args.length) { 69 argv[index - offset] = args[index]; 70 ++index; 71 } 72 break; 73 } 74 } 75 } 76 77 81 public boolean error() { 82 return errorFlag; 83 } 84 85 91 public boolean hasOption(char c) { 92 if (options == null) 93 return false; 94 return options.containsKey(new Character (c)); 95 } 96 97 103 public String option(char c) { 104 return option(c, ""); 105 } 106 107 114 public String option(char c, String defaultValue) { 115 if (options == null) 116 return defaultValue; 117 118 String s; 119 try { 120 Object o = options.get(new Character (c)); 121 if (o == null || !(o instanceof String )) 122 s = defaultValue; 123 else 124 s = (String )o; 125 } 126 catch (Exception e) { 127 s = defaultValue; 128 } 129 return s; 130 } 131 132 139 public String [] args() { 140 return argv; 141 } 142 143 146 public int argc() { 147 if (argv == null) 148 return 0; 149 return argv.length; 150 } 151 158 public String argv(int index) { 159 if (argv == null) 160 return ""; 161 162 return argv[index]; 163 } 164 } 165 | Popular Tags |