ant-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From <Jan.Mate...@rzf.fin-nrw.de>
Subject AW: Using ant to parse text file
Date Fri, 23 Feb 2007 08:02:26 GMT
I played a little bit ...

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

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


public class LoadGroupTask extends Task {

	String prefix;
	File   file;
	String section;
	
	@Override
	public void execute() throws BuildException {
		validate();
		BufferedReader rdr;
		try {
			rdr = new BufferedReader(new FileReader(file));
			boolean needThisSection = false;
			String line = rdr.readLine();
			while (line!=null) {
				line = line.trim();
				if (line.length()>0) {
					if (line.indexOf("=") > 0) {
						if (needThisSection) {
							String[] parts = line.split("=");
							String propName  = (prefix==null)   ? parts[0] : prefix + parts[0];
							String propValue = (parts[1]!=null) ? parts[1] : "";
							log("Setting property " + propName + " -> " + propValue);
							getProject().setNewProperty(propName, propValue);
						}
					} else {
						needThisSection = section.equals(line);
					}
				}
				line = rdr.readLine();
			}
			rdr.close();
		} catch (Exception e) {
			throw new BuildException(e, getLocation());
		}
	}


	protected void validate() {
		if (file==null)      throw new BuildException("You must specify a file to read.");
		if (!file.canRead()) throw new BuildException("Can not read file " + file.getAbsolutePath());
		if (section==null)   throw new BuildException("You must specify a section to read.");
	}
	
	
	public void setFile(File file) {
		this.file = file;
	}
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	public void setSection(String section) {
		this.section = section;
	}
	
	
}


<project>
	<taskdef name="loadgroup" classname="LoadGroupTask" classpath="build/classes"/>
	<loadgroup file="data.txt" prefix="data." section="Test2"/>
	<echoproperties prefix="data"/>
</project>


Jan 

>-----Urspr√ľngliche Nachricht-----
>Von: Kevin Jackson [mailto:foamdino@gmail.com] 
>Gesendet: Freitag, 23. Februar 2007 03:31
>An: Ant Users List
>Betreff: Re: Using ant to parse text file
>
>Hi,
>
>If you don't want to write a custom task in java, you could also try
><scriptdef> and use a scripting language of your choice
>
>http://ant.apache.org/manual/OptionalTasks/scriptdef.html
>
>Kev
>
>---------------------------------------------------------------------
>To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
>For additional commands, e-mail: user-help@ant.apache.org
>
>

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@ant.apache.org
For additional commands, e-mail: user-help@ant.apache.org


Mime
View raw message