---
title: "Java源文件编译示例"
author: "chenyy2050"
date: "2011-08-02T15:20:25Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-08-02T16:08:31Z"
id: 1138197
url: "https://chenyy2050.iteye.com/blog/1138197"
---

java程序编译java源文件

 

JavacCompile文件：

 

package yan.demo.javac;

import java.io.File;  
import java.util.ArrayList;  
import java.util.Arrays;  
import java.util.List;  
import javax.tools.Diagnostic;  
import javax.tools.DiagnosticCollector;  
import javax.tools.FileObject;  
import javax.tools.JavaCompiler;  
import javax.tools.JavaFileObject;  
import javax.tools.StandardJavaFileManager;  
import javax.tools.ToolProvider;

/\**  
 * 編譯java源文件  
 *  
 * @author Chen Ya Yuan  
 * @Email chen.ya.yuan@163.com  
 * @version V1.0  
 \*/  
public class JavacCompile {  
    public static void main(String\[] args) throws Exception {  
        
        compilePackage(  
                Conf.readProperties("project.path")+ Conf.readProperties("src.testentity"),  
                Conf.readProperties("project.libpath"),  
                Conf.readProperties("project.path")+ Conf.readProperties("classes"),  
                Conf.readProperties("project.sourcepath"));  
    }

    /\**  
     * 編譯該包及子包的所有類  
     * @param fromPath  
     *            文件來源  
     * @param libPath  
     *            項目依賴Jar包來源  
     * @param savePath  
     *            編譯後class字節碼文件保存路徑  
     * @param sourcePath  
     *            依賴源碼路徑  
     * @throws Exception  
     \*/  
    public static void compilePackage(String fromPath, String libPath,  
            String savePath,String sourcePath) throws Exception {  
        // 要掃描的文件夾  
        File file = new File(fromPath);  
        // 存儲文件的數據  
        ArrayList&lt;File&gt; allFile = ScanDirectory.getFile(file);  
        String fromFile = "";

        // 设置编译选项  
        Iterable&lt;String&gt; options = getCompileOptions(savePath, libPath, sourcePath);

        for (File f : allFile) {  
            if (f.getName().matches(".\*\\\\.java$")) { // 匹配java格式的文件  
                fromFile = f.getPath(); // java源文件 文件名  
                // 編譯文件  
                compilejava(fromFile, options, savePath);  
            }  
        }  
    }

    /\**  
     * 編譯單個java源文件  
     *  
     * @param fromFile  
     *            java源文件  
     * @param libPath  
     *            項目依賴Jar包來源  
     * @param savePath  
     *            編譯後class字節碼文件保存路徑  
     * @throws Exception  
     \*/  
    public static void compilejava(String fromFile, Iterable&lt;String&gt; options,  
            String savePath) throws Exception {  
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();  
        // 建立DiagnosticCollector對象  
        DiagnosticCollector&lt;JavaFileObject&gt; diagnostics = new DiagnosticCollector&lt;JavaFileObject&gt;();  
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(  
                diagnostics, null, null);

        // 设置编译选项  
        Iterable option = options;

        // 建立用於保存被編譯文件名的對象  
        // 每個文件被保存在一個從JavaFileObject繼承的類中  
        Iterable compilationUnits = fileManager  
                .getJavaFileObjectsFromStrings(Arrays.asList(fromFile));

        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,  
                diagnostics, option, null, compilationUnits);  
        // 編譯源程序  
        boolean success = task.call();  
        for(Diagnostic diagnostic :diagnostics.getDiagnostics()){  
            System.out.format(//格式化編譯不成功時   輸出的相關信息  
                    "Code: %s%n" +  
                    "Kind: %s%n" +  
                    "Position: %s%n" +  
                    "Start Position: %s%n" +  
                    "End Position: %s%n" +  
                    "Source: %s%n" +  
                    "Message:  %s%n",  
                    diagnostic.getCode(), diagnostic.getKind(),  
                    diagnostic.getPosition(), diagnostic.getStartPosition(),  
                    diagnostic.getEndPosition(), diagnostic.getSource(),  
                    diagnostic.getMessage(null)  
            );  
             
        }

        fileManager.close();  
        System.out.println((success) ? fromFile + "  編譯成功" : fromFile  
                + "  編譯失敗");  
    }

    /\**  
     * 设置编译选项  
     *  
     * @param savePath  
     *            編譯後class字節碼文件保存路徑  
     * @param libPath  
     *            項目依賴Jar包來源  
     * @param sourcePath  
     *            依賴源碼路徑  
     * @return  
     \*/  
    public static Iterable&lt;String&gt; getCompileOptions(String savePath,  
            String libPath,String sourcePath) {  
        List&lt;String&gt; options = new ArrayList&lt;String&gt;();  
        File file = new File(savePath);  
        if (!file.exists()) {  
            file.mkdirs(); // 路徑不存在時，創建  
        }

        // 設置編譯後生成的類文件的輸出目錄  
        if (savePath != null) {  
            options.add("-d");  
            options.add(savePath);  
        }

        // 設置用到的第三方類庫的目錄  
        if (libPath != null) {  
            options.add("-classpath");  
            options.add(getLibJar(libPath));  
        }  
         
        //指定查找輸入源文件的位置  
        if(sourcePath!=null){  
            options.add("-sourcepath");  
            options.add(sourcePath);  
        }  
         
        //輸出有關編譯器正在執行的操作的信息  
//        options.add("-verbose");

//        options.add("-target");  
//        options.add("1.6");  
         
        return options;  
    }

    private static String getLibJar(String libPath) {  
        StringBuffer sb = new StringBuffer();  
        // 要掃描的文件夾  
        File file = new File(libPath);  
        // 存儲文件的數據  
        ArrayList&lt;File&gt; allFile = ScanDirectory.getFile(file);  
        for (File f : allFile) {  
            if (f.getName().matches(".\*\\\\.\[jJ]+\[aA]+\[rR]+$")) { // 匹配jar格式的文件  
                sb.append(libPath + File.separator + f.getName() + ";"); // 多個jar文件用分號隔開  
            }  
        }  
         
        return sb.substring(0, sb.lastIndexOf(";"));  
    }  
     
    public JavacCompile(){  
         
    }

}

 

 

 

Conf文件：

 

package yan.demo.javac;

import java.io.FileInputStream;  
import java.util.Enumeration;  
import java.util.HashMap;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.Properties;

/\**  
 *  
 * @author Chen Ya Yuan  
 * @Email chen.ya.yuan@163.com  
 * @version V1.0  
 \*/  
public class Conf {  
 // 根据key读取value  
    public static String readProperties(String key) {  
        Properties props = new Properties();  
        try {  
            String path = Conf.class.getResource("/").getPath();  
            FileInputStream fis =  
                new FileInputStream(path+"config/Conf.chenyy.properties");  
            props.load(fis);  
            String property = props.getProperty(key.trim());  
            if(property!=null){  
                property=property.trim();  
            }  
//            System.out.println(key + value);  
            return property;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return null;  
        }  
    }  
     
    // 读取properties的全部信息  
    public static Map&lt;String,Object&gt; readAllProperties() {  
        Properties props = new Properties();  
        Map&lt;String,Object&gt; map = new HashMap&lt;String,Object&gt;();  
        try {  
            FileInputStream fis = new FileInputStream(Conf.class.getResource("/").getPath()+"config/Conf.chenyy.properties");  
            props.load(fis);  
            Enumeration en = props.propertyNames();  
             
            while (en.hasMoreElements()) {  
                String key = (String) en.nextElement();  
                String property = props.getProperty(key.trim());  
                if(property!=null){  
                    property=property.trim();  
                }  
                map.put(key, property);  
//                System.out.println(key + "   " + property.trim());  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return map;  
    }  
     
    public static void main(String\[] args) {  
        Map&lt;String,Object&gt; map = new HashMap&lt;String,Object&gt;();  
        map = readAllProperties();  
        for(Object object: map.keySet()){   
            System.out.println("key:"+object+"   value:"+map.get(object));  
        }  
    }  
     
}

 

 

Conf.chenyy.properties文件：

\# the project path  
project.path = E:/workspace/project/javacdemo  
project.libpath = E:/workspace/project/javacdemo/lib

\# set search -sourcepath  
project.sourcepath = E:/workspace/project/javacdemo/src

\#  
src.testentity = /src/yan/demo/javac/test

#schema  
schema0 = schema000

#schema1  
schema1 = schema1111

#schema2  
schema2 = schema2222

\#  
classes = /bin/classes