Search code examples
javaindentationpretty-print

How I can indent generated java code java?


I work in a small learning program that generates Java code from a picture. I hold my code in a StringBuilder. I wonder as I can give the text a normal Java code indentation. I could use some library, but not to format the source code, but the String that has generated Java code. Thanks for your attention.


Solution

  • How about the following code:

    import java.io.ByteArrayInputStream;
    
    import com.github.javaparser.JavaParser;
    import com.github.javaparser.ParseException;
    import com.github.javaparser.ast.CompilationUnit;
    
    public static void main(String[] args) throws ParseException {
            String java = new String("public class ThisIsANonWellFormattedJavaClass {public static void main(String[] args){}}");
            CompilationUnit cu = JavaParser.parse(new ByteArrayInputStream(java.getBytes()));
            System.out.println(cu.toString());
        }
    

    It uses a great Java parser library called javaparser