`

自定义Ant Task

阅读更多

版权所有,欢迎转载,转载请注明 : SinFrancis  http://mdev.cc  

 

最近在做一个通过web编译后台程序的东西,编译使用的是ant,由于启动ant后就无法跟踪编译进程,

所以特地写了一个ant的task,进行再build.xml中进行调用,完成整个编译进度跟踪的过程。

 

注意:此代码中使用了json的数据格式,需要导入json-lib及相关的类库包。

 

并且此Task会将相关编译进度信息写入指定的文件(json格式),然后让web进行取得此文件内容即可。

 

 

用法:将此类打成jar包,配置到classpath或者直接放到ant_home的lib下,别忘记json相关的类库。

 

在build.xml文件中定义task:

 

 

<taskdef name=" progresstask" classname="cc.mdev.ant.ProgressTask"  />
 

运行此任务:

 

 

<progresstask message="Build code..." progressFilePath="${webapp}/test/compile.txt"/>
 

 

 

Task的代码:

 

 

package cc.mdev.ant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import net.sf.json.JSONObject;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class ProgressTask extends Task {

	/**
	 * 進度文件的全路徑
	 */
	private String progressFilePath;

	/**
	 * 進度信息
	 */
	private String message;

	
	
	@Override
	public void execute() throws BuildException {
//		System.out.println("Progresds  Task!  " + progressFilePath + "   "
//				+ message);
		
		String content = null;
		FileInputStream fis=null;
		//讀取文件
		try {
			fis = new FileInputStream(progressFilePath);
			byte[] b = new byte[fis.available()];
			fis.read(b);
			content = new String(b);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}finally{
			try {
				if(fis!=null)
				fis.close();
			} catch (IOException e) {
			}
		}
		JSONObject jsonObject = JSONObject.fromObject( content );  
		jsonObject.put("message", message);
		try {
			saveJsonObject2File(jsonObject,progressFilePath);
		} catch (IOException e) {
		}
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getProgressFilePath() {
		return progressFilePath;
	}

	public void setProgressFilePath(String progressFilePath) {
		this.progressFilePath = progressFilePath;
	}
	
	public  void saveJsonObject2File(JSONObject jsonObject,String filePath) throws IOException{
		if(filePath==null)return;
		File f = new File(filePath);
		if(!f.exists()){
			f.createNewFile();
		}
		Writer writer = new FileWriter(filePath);
		jsonObject.write(writer);
		writer.close();
}

}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics