Ant builds Java projects and ant builds java

Source: Internet
Author: User

Ant builds Java projects and ant builds java
Ant builds a Java Project

We create a HelloWorld project, and send the source file. java to src. After compilation, the bytecode. class is put into the bin, and the corresponding jar package is put into the exe directory.
First, use the command line to build the project:
1. Create the src directory
Md src
2. Store the source file HelloWorld. java in the src directory. The HelloWorld class package is named com. tghz. test.
Create the package name path, cd src, md com, cd com, md tghz, cd tghz, and md test, and store HelloWorld. java to the current directory.

//HelloWorld.java   public class HelloWorld{      public static void main(String[] args){     System.out.println("Hello World");  }   }

3. Create the bin directory and store the compiled bytecode HelloWorld. class in the directory.
Md bin
Switch to the project directory,
Javac-sourcepath src \ com \ tghz \ test-d bin src \ com \ tghz \ test \ HelloWorld. java (Command Format: java-sourcepath source file directory-d destination file storage directory source file. java)
The corresponding directory is automatically generated under the bin directory based on the package name of HelloWorld. java.
4. Generate the jar package and save it to the exe directory.
Switch to the bytecode. class directory, that is, the bin directory.
First, create a configuration file for the jar package, which describes the Main Class to be executed in the format of Main-Class: space package name. the main class name enters a line feed, which is in the same directory as the package file.
Jar package configuration file: mainconfig.txt
Main-Class: com. tghz. test. HelloWorld

Execute jar-cvfm HelloWorld. jar (generated jar file name) mainconfig.txt (jar package configuration file) com. tghz. test (package name)
In this way, the jar file is generated.
If there are multiple. class files, you need to create the configuration file mymanifest and archive all the files in the bin directory to classes. jar. Jar cvfm classes. jar mymanifest-C bin.
After the execution is successful, the jar package is generated, and the jar package configuration in MANIFEST. MF in the META-INF folder in the jar can be seen.

Next we will use Ant to build a Java Project
Ant's build script file is written in XML. The default value is build. xml. Build. xml contains a root node project, indicating a project. Each build file can contain only one project node element.
The project node defines one or more targets, indicating different modules. Target has a set of tasks. Each task is a piece of executable code.
Using ant to build a simple Java project contains three parts:
1. clean Delete the generated bytecode. class file and jar file, so that we will not conflict with the new file.
2. Compile the source file to generate the. class file.
3. Package and generate a jar File
4. Run the java Project
There are four target modules in our build. xml project: clean, compile, jar, and run.
The following describes the build. xml file in detail:
<? Xml version = "1.0" encoding = "UTF-8"?> <Project name = "HelloWorld" default = "run" basedir = "."> <! -- Property is generally the variable to be used later --> <property name = "src. dir "value =" src "/> <property name =" bin. dir "value =" bin "/> <property name =" jar. dir "value =" exe "/> <property name =" main-class "value =" HelloWorld "/> <! -- "Clean" is used to clear the generated bytecode and jar files, in this way, no duplicate is generated --> <target name = "clean"> <delete dir = "$ {bin. dir} "/> <delete dir =" $ {jar. dir} "/> <echo message =" clean the bin and exe "/> </target> <! -- "Compile" is used to compile the source. java file --> <target name = "compile" depends = "clean"> <mkdir dir = "$ {bin. dir} "/> <javac srcdir =" $ {src. dir} "destdir =" $ {bin. dir} "/> <echo message =" compile done! "/> </Target> <! -- "Jar" is used to package and generate jar --> <target name = "jar" depends = "compile"> <mkdir dir = "$ {jar. dir} "/> <jar destfile =" $ {jar. dir}/HelloWorld. jar "basedir =" $ {bin. dir} "> <! -- Use the manifest node to configure the jar package --> <manifest> <attribute name = "Main-Class" Value = "$ {main-class}"/> </manifest> </ jar> <echo message = "created jar file"/> </target> <! -- "Run": compile, package and generate jar, and run jar --> <target name = "run" depends = "jar"> <java classname = "com. tghz. test. helloWorld "classpath =" $ {jar. dir}/HelloWorld. jar "/> </target> </project>
When compiling the source files in src, com/tghz/test/HelloWorld. class is automatically generated in the bin directory according to the package name in the code. Javac srcdir = "$ {src. dir}" (source file directory) destdir = "$ {bin. dir}" (target file directory)
When generating a jar package, use the manifest node to configure the jar package and specify the name of the main class. Each jar contains a configuration file to specify the jar attributes.
Jar destfile = "$ {jar. dir}/HelloWorld. jar "(name and relative path of the generated jar file) basedir =" $ {bin. dir} "(specify the current base path)
Create a jar file named destfile and add all the files under the basedir directory to it. When running the specified jar file, you must specify the complete class name path and jar package name and path java classname = "com. tghz. test. helloWorld "(Class Name) classpath =" $ {jar. dir}/HelloWorld. jar "(jar package name)
Go to the directory where the build. xml file is located from the command line. Execute ant and search for and execute the build. xml file by default. Sometimes it is more convenient to generate a file with another name. In that case, you need to use the-buildfile <file> parameter (-f <file> is its abbreviated form) for Ant ). We can also specify some modules in the execution project, instead of all. Such as ant compile.


Ant support in Eclipse
Eclipse, an open-source Project, provides a lot of support for Ant. The core is the Ant editor of Eclipse. You can open the build. xml file in Ant Editor and execute it directly. Then, the script in xml will be executed.


Ant automatically compiles and packages android Projects

Ant support for existing Android Projects

Go to the sdk/tools directory and run the android update project -- name AntTest (project name) -- path F: \ workspace2 \ AntTest1 (project path) command to generate a build in this android project. xml and local. properties. The local. properties file shows the directory of our android SDK.

Build. xml is the most important script for ant building. When you open it, you will find that there are only a few useful lines in it, because the build is generated. the xml script references the built-in build script of the android sdk. <import file = "$ {sdk. dir}/tools/ant/build. xml "/>, the specific directory is in the {sdk directory}/tools/ant/build. xml.
In this way, our project supports ant compilation and packaging.
Go to our project directory and execute ant debug to generate a test apk. By default, the debug key is used for signature, and the generated apk is placed in the bin directory.
Execute ant releaseto generate an unsigned apk(your_prject_name-release-unsigned.apk ).


Other library projects are referenced in the project:

If a third-party jar package is referenced in the project, you only need to put the jar package under the libs folder. The third-party jar package will be automatically added during ant compilation and packaging. However, if our android project references other library projects, we should first add one more parameter when executing the android update command: subprojects

The first thing we need to do is to make the reference library project support ant compilation and packaging, and execute android update lib-project -- path (project path). Note that the parameter is lib-project.
Then return to the original project and enter the command "android update project -- name project name-path project path -- subprojects". Then, OK.


Third-party jar packages in the user library
Normally, you can execute ant debug directly in the root directory of the project to perform a normal build. The default classpath includes all jar files in the libs directory. However, if user library is used in the project or external jar files are referenced, problems may occur during compilation,
Because user library and other jar files are not automatically included in classpath, you need to expand the ant path variable and add your own jar files to classpath.
By checking the build. xml compilation script provided by the sdk, you can find that the classpath used by javac is defined as follows:
<path id="project.javac.classpath">    <path refid="project.all.jars.path"></path>    <path refid="tested.project.classpath"></path></path><javac encoding="${java.encoding}"        source="${java.source}" target="${java.target}"        debug="true" extdirs="" includeantruntime="false"        destdir="${out.classes.absolute.dir}"        bootclasspathref="project.target.class.path"        verbose="${verbose}"        classpathref="project.javac.classpath"        fork="${need.javac.fork}">    <src path="${source.absolute.dir}"></src>    <src path="${gen.absolute.dir}"></src>    <compilerarg line="${java.compilerargs}"></compilerarg></javac>

Project. all. jars. path contains all jar files. We can introduce other jar files by redefining this variable in build. xml under the project directory.
For example, in my project, the ormlite ORM library is referenced. To view the source code using "attach source" in development, the jar file cannot be placed in the libs directory, because Eclipse does not allow "attach source" to the jar file in the libs directory ". Therefore, I put this file in the libs/ormlite directory. To add these two jar files to the classpath, I need to redefine the project. all. jars. path element.
The basic idea is to redefine the pre-compile target and redefine the value of project. all. jars. path.
Where can I write this code? M_rules.xml under the current directory is referenced in build. xml of each project. Then we create a custom_rules.xml file under the root directory of the project. The content is as follows:
<?xml version="1.0" encoding="UTF-8"?><project name="custom_rules" default="release"><target name="-pre-compile"><echo message="JARPATH=${toString:project.all.jars.path}"></echo><echo message="JARPATH=${jar.libs.dir}"></echo>    <property name="ormlite.dir" value="${jar.libs.dir}/ormlite"> </property>    <path id="ormlite.lib">        <path path="${toString:project.all.jars.path}"></path>        <pathelement location="${ormlite.dir}/ormlite-android-4.41.jar"></pathelement>         <pathelement location="${ormlite.dir}/ormlite-core-4.41.jar"></pathelement>    </path>    <path id="project.all.jars.path">        <path refid="ormlite.lib"></path>    </path>    <echo message="JARPATH=${toString:project.all.jars.path}"></echo></target></project>

Signature and channel package
Based on ant's automatic compilation and packaging of existing android projects, you can add signature information and automatically package channel packages when ant is packaging applications.
Add signature information
Create an ant under the root directory of the project. in the properties file, enter the following content. The keystore password and alias password can be unspecified (leakage prevention), so you are required to enter the key during command execution.
# The keystore path must use the forward slash key. store = "E:/wp_android_sample/me. key "# keystore password # key. store. password = ***** # alias Name key. alias = me # alias password # key. alias. password = ******


Running the ant release command in the root directory of the project will help you generate an apk(your_project_name-release.apk) signed and alignedin the bin directory.


Automatically package channel packages
Batch cyclic packaging requires a function similar to the for loop. There is no related For loop Task in the Ant core package, that is, the for loop is not supported, but ant supports third-party extension packages, to support more other functions.
So we need to download the corresponding extension packages that support the for loop. You can use the open-source Ant-contrib package. : Http://ant-contrib.sourceforge.net /.
Put the downloaded jar file to the ant lib directory. Next we can package the channel package. The specific method is:
(1) first, add the attributes market_channels (channel list, separated by commas) and version (application version name) to the ant. properties file)
# Channel market list market_channels = 91,360, wandoujia, baidu # version = 1.2.1

(2) Add the following code to build. xml of our project:
<! -- Channel package packaging script ant deploy --> <taskdef resource = "net/sf/antcontrib. properties "> <classpath> <pathelement location =" lib/ant-contrib-1.0b3.jar "/> </classpath> </taskdef> <target name =" deploy "> <foreach target =" modify_manifest" list = "$ {market_channels}" param = "channel" delimiter = ", "> </foreach> </target> <target name =" modify_manifest "> <replaceregexp flags =" g "byline =" false "> <! -- The matched content is android: value = "*****" android: name = "UMENG_CHANNEL" --> <regexp pattern = 'android: value = "(. *) "android: name =" UMENG_CHANNEL "'/> <! -- Replace it with android: value = "channel name" android: name = "UMENG_CHANNEL" --> <substitution expression = 'android: value = "$ {channel}" android: name = "UMENG_CHANNEL" '/> <! -- The file to be matched by the regular expression is AndroidManifest. xml --> <fileset dir = "" includes = "AndroidManifest. xml "/> </replaceregexp> <property name =" out. release. file "location =" $ {out. absolute. dir}/{ant.project.name=_{{channel}.apk "/> <! -- Package --> <antcall target = "release"/> <! -- Export the channel package to the bin/out directory --> <copy tofile = "$ {out. absolute. dir}/out/login using ant.project.name=v??version=-{channel=.apk "file =" bin/login using ant.project.name=-release.apk "/> </target>
Running the ant deploy command in the root directory of the project will help you with the signature packages of various channels (to automatically execute the entire process, ant. the keystore password in the properties file can be specified, so you do not need to manually enter the password during execution), in the out directory of the bin directory.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.