javaapache-commonsapache-commons-cli

How do i 'get' help string from commons cli instead of 'print'


I know, the below code will generate and print the help text to the console

 HelpFormatter formatter = new HelpFormatter();
 formatter.printHelp("myapp", header, options, footer, true);

but how do i get the help text as a String object. I am expecting something like

formatter.getHelp("myapp", header, options, footer, true);

Is there any method hidden in the CLI API ? or Is there any way to get the help text instead of printing it to the console.


Solution

  • You can do the following

        HelpFormatter formatter = new HelpFormatter();
    
        StringWriter out = new StringWriter();
        PrintWriter pw = new PrintWriter(out);
    
        formatter.printHelp(pw, 80, "myapp", "test-header", opts,
                formatter.getLeftPadding(), formatter.getDescPadding(), "test-footer", true);
        pw.flush();
    
        System.out.println("Had usage: " + out.toString());
    

    See the JavaDoc for details.