java_format

This script will format the *.java files in the given directory ($PWD if not given) and its subdirectories according to the Google Java Style.

Both module-info.java and package-info.java are formatted as well.

This script needs internet access if it does not find the cached JAR file.

It will download and cache the google-java-format JAR.

The JAR is cached in the following location (in order of preference):

  • $GOOGLE_JAVA_FORMAT_HOME if $GOOGLE_JAVA_FORMAT_HOME is set

  • $XDG_CACHE_HOME/googlejavaformat if $XDG_CACHE_HOME is set

  • $HOME/Library/Application Support/Google/googlejavaformat on MacOS

  • $HOME/.m2/repository/com/google/googlejavaformat-all-deps

If you are using Gradle or Maven you might want to use Spotless instead of this script:

Gradle
plugins {
  id("com.diffplug.spotless") version "..."
}

spotless {
  java {
    googleJavaFormat()
  }
}
Maven
<plugin>
  <groupId>com.diffplug.spotless</groupId>
  <artifactId>spotless-maven-plugin</artifactId>
  <version>...</version>
  <configuration>
...
    <java>
      <googleJavaFormat/>
    </java>
  </configuration>
</plugin>

If you are using a JetBrains IDE you might want to use the google-java-format plugin.

Usage

$ scripts/java/java_format.sh
$ scripts/java/java_format.sh /tmp/example/src/main/java

Prerequisites