使用 shell 脚本的 Java 代码格式化

标签 java unix shell scripting

我知道这很愚蠢,但我无法克服好奇心。是否可以编写一个shell脚本来格式化一段java代码?

例如,如果用户在代码中写入:

    public class Super{
    public static void main(String[] args){
    System.out.println("Hello world");
    int a=0;
    if(a==100)
    {
    System.out.println("Hello world");
    }
    else
    {
    System.out.println("Hello world with else");
    }
    }
}

我想编写一个 shell 脚本,使代码像这样。

 public class Super
 {
  public static void main(String[] args)
  {
   System.out.println("Hello world");
   int a=0;
   if(a==100){
    System.out.println("Hello world");
   }
   else{
    System.out.println("Hello world with else");
   }
}

准确地说,我们应该更改花括号的格式。如果它是 try/catch 或控制结构,我们应该将它更改为同一行,如果它是函数/方法/类,它应该在下一行。我对 sed 和 awk 知之甚少,它们可以如此轻松地完成这项任务。我也知道这可以使用 eclipse 来完成。

最佳答案

好吧,我有一些空闲时间,所以我决定重温我过去的 Linux 时光:]

在阅读了一些关于 awk 和 sed 的内容后,我决定同时使用两者可能更好,因为在 awk 中添加缩进和在 sed 中解析字符串更容易。

这是格式化源文件的 ~/sed_script:

    # delete indentation
    s/^ \+//g

    # format lines with class
    s/^\(.\+class.\+\) *\({.*\)$/\1\n\2/g

    # format lines with methods
    s/^\(public\|private\)\( \+static\)\?\( \+void\)\? \+\(.\+(.*)\) *\({.*\)$/\1\2\3 \4\n\5/g

    # format lines with other structures
    /^\(if\|else\|for\|while\|case\|do\|try\)\([^{]*\)$/,+1 {   # get lines not containing '{'
                                                            # along with the next line
      /.*{.*/ d             # delete the next line with '{'
      s/\([^{]*\)/\1 {/g    # and add '{' to the first line
    }

这是添加缩进的 ~/awk_script:

    BEGIN { depth = 0 }
    /}/   { depth = depth - 1 }
          {
              getPrefix(depth)
              print prefix $0
          }
    /{/   { depth = depth + 1 }

          function getPrefix(depth) {
              prefix = ""
              for (i = 0; i < depth; i++) { prefix = prefix "    "}
              return prefix
          }

然后你就这样使用它们:

    > sed -f ~/sed_script ~/file_to_format > ~/.tmp_sed
    > awk -f ~/awk_script ~/.tmp_sed

它远不是合适的格式化工具,但我希望它可以作为示例脚本供引用:]祝你学习顺利。

关于使用 shell 脚本的 Java 代码格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1137946/

相关文章:

linux - bash 脚本多重条件

java - 错误: Multiple annotations found at this line:

c - 关于在我的虚拟 shell 中使用 fork() 和子进程的后台进程

unix - 无法在 unix 中执行二进制文件

unix - 在列/字段中替换 AWK 中的单引号

shell - 使用 awk 打印匹配键的列范围

java - 在Java中打印线程实例是什么意思?

Java 使用 .class

java - Android Studio 无法识别字符串

linux - 无法在 bash 脚本中生成 grep 命令结果