1 import gnu.getopt.LongOpt; 2 import gnu.getopt.Getopt; 3 4 10 11 public class GetoptDemo 12 { 13 14 public static void 15 main(String [] argv) 16 { 17 int c; 18 String arg; 19 LongOpt[] longopts = new LongOpt[3]; 20 StringBuffer sb = new StringBuffer (); 22 longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'); 23 longopts[1] = new LongOpt("outputdir", LongOpt.REQUIRED_ARGUMENT, sb, 'o'); 24 longopts[2] = new LongOpt("maximum", LongOpt.OPTIONAL_ARGUMENT, null, 2); 25 Getopt g = new Getopt("testprog", argv, "-:bc::d:hW;", longopts); 27 g.setOpterr(false); while ((c = g.getopt()) != -1) 30 switch (c) 31 { 32 case 0: 33 arg = g.getOptarg(); 34 System.out.println("Got long option with value '" + 35 (char)(new Integer (sb.toString())).intValue() 36 + "' with argument " + 37 ((arg != null) ? arg : "null")); 38 break; 39 case 1: 41 System.out.println("I see you have return in order set and that " + 42 "a non-option argv element was just found " + 43 "with the value '" + g.getOptarg() + "'"); 44 break; 45 case 2: 47 arg = g.getOptarg(); 48 System.out.println("I know this, but pretend I didn't"); 49 System.out.println("We picked option " + 50 longopts[g.getLongind()].getName() + 51 " with value " + 52 ((arg != null) ? arg : "null")); 53 break; 54 case 'b': 56 System.out.println("You picked plain old option " + (char)c); 57 break; 58 case 'c': 60 case 'd': 61 arg = g.getOptarg(); 62 System.out.println("You picked option '" + (char)c + 63 "' with argument " + 64 ((arg != null) ? arg : "null")); 65 break; 66 case 'h': 68 System.out.println("I see you asked for help"); 69 break; 70 case 'W': 72 System.out.println("Hmmm. You tried a -W with an incorrect long " + 73 "option name"); 74 break; 75 case ':': 77 System.out.println("Doh! You need an argument for option " + 78 (char)g.getOptopt()); 79 break; 80 case '?': 82 System.out.println("The option '" + (char)g.getOptopt() + 83 "' is not valid"); 84 break; 85 default: 87 System.out.println("getopt() returned " + c); 88 break; 89 } 90 for (int i = g.getOptind(); i < argv.length ; i++) 92 System.out.println("Non option argv element: " + argv[i] + "\n"); 93 } 94 95 } 97 98 | Popular Tags |