stjimmy
stjimmy

Reputation: 41

Programmatically format the java code using java

I would like to format strings which contains codes like:

 "function() { for(i=0;i<n;i++){ return i; }}"

The point is to put new lines to each ; except in the for loop, so the formatted output should be something like this:

function() {
   for(i=0;i<n;i++){
    return i;
  } 
 } 

Is there any written function for this, or I have to loop through the whole string?

Upvotes: 2

Views: 1735

Answers (1)

Sasikumar Murugesan
Sasikumar Murugesan

Reputation: 4520

You have to use google-java-format-1.5.jar and google-java-format-1.5-all-deps.jar

and see the below example code

public class Main {
   public static void main(String[] args) {
      Formatter formatter = new Formatter();
      try {
        System.out.println(formatter.formatSource("public class Test{public static void main(String[] args) {String s;}}"));
      } catch (FormatterException e) {
        e.printStackTrace();
    }
 }

}

and output will be

public class Test {
  public static void main(String[] args) {
     String s;
  }
}

Sample working code Sample

Hope this would helps to you

Upvotes: 3

Related Questions