遍历文件夹生成XML
import java.io.*;import java.util.Stack;import org.jdom.*;import org.jdom.output.*;public class XMLWriter {public static void write(File rootDirectory, String XMLPath)throws IOException, JDOMException {/* * 创建文档,根节点是<Source></Source> */Document Doc;Element root = new Element("Source");Doc = new Document(root);/* * 按层次遍历文件目录树 */int count;File tempFile;DirectoryElement tempDirectory;Stack<File> fileStack = new Stack<File>();Stack<Element> directoryElements = new Stack<Element>();File files[];fileStack.push(rootDirectory);directoryElements.push(root);while (!fileStack.isEmpty()) {count = 0;tempFile = fileStack.pop();tempDirectory = new DirectoryElement(tempFile);directoryElements.pop().addContent(tempDirectory);files = tempFile.listFiles();for (int i = 0; i < files.length; i++) {if (files[i].isDirectory()) {fileStack.push(files[i]);directoryElements.push(tempDirectory);} else {tempDirectory.addContent(new FileElement(files[i]));++count;}}//tempDirectory.setAttribute("FileCount", Integer.toString(count));}/* * 生成和保存xml文件 */XMLOutputter XMLOut = new XMLOutputter();// XMLOut.setEncoding("gb2312");File XMLOutput = new File(XMLPath);XMLOut.output(Doc, new FileOutputStream(XMLOutput));System.out.println("XML Created!");}public static void main(String[] args) {try {XMLWriter.write(new File("D:\\zxm"), "D:\\file.xml");} catch (Exception e) {System.out.println(e.getMessage());}}}下面两个雷继承自Element类,用于生成XML的文件节点和文件夹节点,使用的是jdom
import java.io.File;import java.util.Date;import org.jdom.Element;/** * @Description: TODO(用于生成XML的文件夹节点) */@SuppressWarnings("serial")public class DirectoryElement extends Element { public DirectoryElement(File file) { super("Directory"); this.setAttribute("AbsolutePath",file.getAbsolutePath()); this.setAttribute("pathName",file.getName()); // this.setAttribute("Hidden",Boolean.toString(file.isHidden()));// this.setAttribute("canWrite",Boolean.toString(file.canWrite()));// this.setAttribute("canRead",Boolean.toString(file.canRead())); // this.setAttribute("LastModified",(new Date(file.lastModified())).toString());// this.addContent(file.getName()); }}import java.io.File;import java.util.Date;import org.jdom.Element;/** * @Description: TODO(用于生成XML的文件节点) */@SuppressWarnings("serial")public class FileElement extends Element { public FileElement(File file) { super("File");// this.setAttribute("AbsolutePath",file.getAbsolutePath()); this.setAttribute("fileName",file.getName());// this.setAttribute("Hidden",Boolean.toString(file.isHidden()));// this.setAttribute("canWrite",Boolean.toString(file.canWrite()));// this.setAttribute("canRead",Boolean.toString(file.canRead())); // this.setAttribute("TotalSpace",Long.toString(file.length()/1024)+"KB");// this.setAttribute("LastModified",(new Date(file.lastModified())).toString()); // this.addContent(file.getName()); }}