一直都是使用Eclipse或IntelliJ IDEA,结果离开了编译工具完全不会使用javac进行编译。最近,为了一个自动化编译不得不使用命令行进行编译。今天这个示例是一个简单的将指定文件夹的代码编译成class文件,然后再打包成jar的例子。

给定示例java项目的文件夹结构如下所示。

.
├── build
│   └── classes
├── jars
├── makefile.py
└── src
    └── hao
        ├── Hello.java
        └── utils
            └── Timer.java

执行makefile.py以后,将./src目录下的所有java源程序编码,放在./buil/classes目录下,然后将编译后的文件打包成hao.jar放在 ./jars目录下,如下所示。

.
├── build
│   └── classes
│       ├── Hello.class
│       └── hao
│           ├── Hello.class
│           └── utils
│               └── Timer.class
├── jars
│   └── hao.jar
├── makefile.py
└── src
    └── hao
        ├── Hello.java
        └── utils
            └── Timer.java

打包所使用的 py文件makefile.py 的内容如下所示。

import os

# input directory and output directory.
srcDir = "./src" # source code
outDir = "./build/classes" # output classes

# java files to be compiled, note that:
# "hao" corresponds to *.java files stored in ./src/hao
# "hao.utils" corresponds to *.java file stored in ./src/hao/utils
srcs = ["hao", "hao.utils"]

# Format inputs. For example, 
# hao -> ./src/hao/*.java
# hao.utils -> ./src/hao/*.java
classpath = srcDir
for i in range(len(srcs)):
    srcs[i] = os.path.join(os.path.join(srcDir, srcs[i].replace(".", "/"), "*.java"))

# create the compiling command
compileCmd = "javac -d {0} -cp {1} {2}".format(outDir, classpath, " ".join(srcs))

# compile
print(compileCmd)
os.system(compileCmd)

jarCmd = "jar cvf ./jars/hao.jar -C ./build/classes ."
os.system(jarCmd)
print("Compiled.")