Home > other >  JavaParser removes empty lines
JavaParser removes empty lines

Time:01-28

I am using JavaParser with with the following dependency:

<dependency>
  <groupId>com.github.javaparser</groupId>
  <artifactId>javaparser-core</artifactId>
  <version>3.24.0</version>
</dependency>

When I try to use it with the following class (parsing itself)...

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Some comment.
 */
public class JavaParserPlayground {
  public static void main(String[] args) throws IOException {
    // Some comment.
    String source = Files.readString(Paths.get("path\\JavaParserPlayground.java"),
      StandardCharsets.UTF_8);

    // Some comment.
    JavaParser parser = new JavaParser();
    ParseResult<CompilationUnit> parseResult = parser.parse(source);

    // Some comment.
    CompilationUnit unit = parseResult.getResult().orElseThrow();
    System.out.println(unit.toString());
  }
}

...then I get the following result:

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Some comment.
 */
public class JavaParserPlayground {

    public static void main(String[] args) throws IOException {
        // Some comment.
        String source = Files.readString(Paths.get("path\\JavaParserPlayground.java"), StandardCharsets.UTF_8);
        // Some comment.
        JavaParser parser = new JavaParser();
        ParseResult<CompilationUnit> parseResult = parser.parse(source);
        // Some comment.
        CompilationUnit unit = parseResult.getResult().orElseThrow();
        System.out.println(unit.toString());
    }
}

My problem is that I need the original output with all original line breaks. But it removes some empty lines (between import statements, within the method), removes line breaks (within source assignment) and adss empty lines (before main method).

More of it: The original source has 2 spaces indentation, the printed source 4 spaces.

Is it possible to force the original code structure?

CodePudding user response:

You want to use the LexicalPreservingPrinter. Here is the setup documentation. Basically, you can just add it on to the end of the chain like so (when everything is working as intended):

CompilationUnit lpp = LexicalPreservingPrinter.setup(unit);
System.out.println(LexicalPreservingPrinter.print(lpp));
  •  Tags:  
  • Related