package com.shengsiyuan.ant.custom;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
/**
* Ant扩展类,对文本的行进行排列
*
* @author Kevin
*
*/
public class FileSorter extends Task {
/**
* 源文件,从标签通过getSrcFile传过来是字符串,此处会自动转化为File对象
*/
private File srcFile;
/**
* 排序好的文件
*/
private File destFile;
/**
* 扩展Ant的java类必须覆盖execute() in Task
*/
@Override
public void execute() throws BuildException {
// 构建输入和输出流
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(
srcFile));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(
destFile));
List<String> txtList = new ArrayList<String>();
String txtLine = bufferedReader.readLine();
// 把源文件一行行读取到list
while (txtLine != null) {
txtList.add(txtLine);
txtLine = bufferedReader.readLine();
}
// 排序
Collections.sort(txtList);
// 把排好序的list放入目的文件
for (String stringList : txtList) {
bufferedWriter.write(stringList);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new BuildException("构建输入输出流失败!");
} catch (IOException e) {
e.printStackTrace();
throw new BuildException("构建输入输出流失败!");
}
}
public File getSrcFile() {
return srcFile;
}
public void setSrcFile(File srcFile) {
this.srcFile = srcFile;
}
public File getDestFile() {
return destFile;
}
public void setDestFile(File destFile) {
this.destFile = destFile;
}
}
1.扩展ant,对文件内容的行进行排序:java类
最新推荐文章于 2022-11-18 14:04:40 发布