这里是我自己写的一个简单的文件合成器,把n多文件路径配置在xml中,Java解析后读出来写到第一个文件中去。
xml配置文件如下:
path.xml
<?xml version="1.0" encoding="gbk"?>
<files>
<file path="d:\123.txt"></file>
<file path="d:\124.txt"></file>
<file path="d:\125.txt"></file>
</files>
解析的Java代码如下:
ReadAll.java
package javaIOTest;
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
imp
public class ReadAll {
private ReadAll(String xmlFile) {
dispose(xmlFile);
}
public HashMap<String, String> iterateWholeXML(String filename) {
SAXReader saxReader = new SAXReader();
HashMap<String, String> hm = new HashMap<String, String>();
try {
Document document = saxReader.read(new File(filename));
Element root = document.getRootElement();
int num = -1;
System.out.println("开始解析......");
for (Iterator iter = root.elementIterator(); iter.hasNext();) {
Element element = (Element) iter.next();
num++;
Attribute pathAttr = element.attribute("path");
if (pathAttr != null) {
String path = pathAttr.getValue();
if (path != null && !path.equals("")) {
hm.put(pathAttr.getName() + num, path);
} else {
hm.put(pathAttr.getName() + num, "\123");
}
}
}
return hm;
} catch (DocumentException e) {
e.printStackTrace();
}
return hm;
}
private void dispose(String xmlFile) {
readFile(iterateWholeXML(xmlFile));
}
public void readFile(HashMap<String, String> fileMap) {
FileReader fr = null;
FileWriter fw = null;
BufferedWriter bw = null;
BufferedReader br = null;
String str=null;
try {
File file0 = null;
StringBuffer sb = new StringBuffer();
System.out.println("开始读取......");
for (String ss : fileMap.keySet()) {
System.out.println("正在合并......");
System.out.println(ss + ":" + fileMap.get(ss));
if("path0".equals(ss)){
file0 = new File(fileMap.get(ss));
continue;
}
File file = new File(fileMap.get(ss));
fr = new FileReader(file);
br = new BufferedReader(fr);
do{
str = br.readLine();
sb.append(str);
sb.append("
");
}while(br.readLine()==null);
sb.append("
");
}
fw = new FileWriter(file0, true);
bw = new BufferedWriter(fw);
bw.write(sb.toString());
bw.flush();
System.out.println("合并结束......");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ReadAll("d:\path.xml");
}
}
在执行的时候确保你的配置文件的路径和main方法中的路径一致。