Ant - Comment créer un projet Java

Ant - Comment créer un projet Java

Dans ce didacticiel, nous allons vous montrer comment utiliser l'outil de génération Ant pour gérer un projet Java, le compiler et le regrouper dans un fichier Jar.

Technologies utilisées:

  1. Eclipse 4.2

  2. Ant 1.9.4

  3. JDK 1.7

1. Créer un projet Java

Dans Eclipse IDE, créez un nouveau projet Java nommé «AntDateUtils».

ant-java-project

2. Code source Java

Créez une nouvelle classe Java pour imprimer la date actuelle:

src/com/example/core/utils/DateUtils.java

package com.example.core.utils;

import java.util.Date;

public class DateUtils {

    public static void main(String[] args) {

        System.out.println(getLocalCurrentDate());

    }

    private static Date getLocalCurrentDate() {
        return new Date();
    }

}

3. build.xml

Créez un nouveaubuild.xml dans le dossier racine du projet, lisez le commentaire pour plus d'explications.

build.xml


    
        Create a Java Project (JAR) with Ant build script
    

    

    
    

    
    

    
    

    
        
        
        
        
    

    
        
        
    

    

        
        

        
        
            
            
            
            
        
    

    
        
        
    

    
    

4. Ant Build Scripts

Terminé, essayez quelques commandes de Ant

4.1 Compile the source code

$ ant compile

build.xml


    

4.2 Package the project into an executable Jar file

$ ant dist

build.xml


    
    
      
        
      
    

4.3 Delete folders

$ ant clean

build.xml


    
    

4.4 If no options, the default target will be executed, in this example, the default target is main

build.xml


    ...
    
$ ant

Sortie

Buildfile: /Users/example/Documents/workspace/AntDateUtils/build.xml
clean:
   [delete] Deleting directory /Users/example/Documents/workspace/AntDateUtils/bin
   [delete] Deleting directory /Users/example/Documents/workspace/AntDateUtils/dist
init:
    [mkdir] Created dir: /Users/example/Documents/workspace/AntDateUtils/bin
compile:
    [javac] Compiling 1 source file to /Users/example/Documents/workspace/AntDateUtils/bin
dist:
    [mkdir] Created dir: /Users/example/Documents/workspace/AntDateUtils/dist
      [jar] Building jar: /Users/example/Documents/workspace/AntDateUtils/dist/DateUtils-20141030.jar
main:
BUILD SUCCESSFUL
Total time: 1 second

Structure finale du répertoire

ant-java-project-final

5. Test

5.1 Run a class inside a Jar file.

$ pwd
/Users/example/Documents/workspace/AntDateUtils

$ java -cp dist/DateUtils-20141030.jar com.example.core.utils.DateUtils
Thu Oct 30 17:39:21 MYT 2014

5.2 Run the executable Jar file

$ pwd
/Users/example/Documents/workspace/AntDateUtils

$ java -jar dist/DateUtils-20141030.jar
Thu Oct 30 17:40:21 MYT 2014

Télécharger le code source

Téléchargez-le -AntDateUtils.zip (6 Ko)