package WildCat.Xml.com;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class readFile1_1 {
private static ArrayList filelist = new ArrayList();
public static Element first1=null;
public static void main(String[] args) throws IOException {
writeXml("RAR/jim","WildCat","RAR.xml");
}
//该函数有两个参数,第一个是文件路径;一个是父亲节点的名字
public static void refreshFileList(String strPath,Element first) throws IOException {
File dir = new File(strPath);
File[] files = dir.listFiles();
// Document document=DocumentHelper.createDocument(first);
if (files == null){
first1=first.addElement("first");
first1.addAttribute("name", files.toString());
first1.addAttribute("id", "0");
return;
}
//递归遍历文件夹
for (int i = 0; i < files.length; i++) {
if (!files[i].isDirectory()){
first1=first.addElement("first1");
String num=String.valueOf(i+1);
first1.addAttribute("name", files[i].getName());
first1.addAttribute("id", num);
}
}
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
//继续向里进
if(null!=files[i]){
first1=first.addElement("first1");
String num=String.valueOf(i+1);
first1.addAttribute("name", files[i].getName());
first1.addAttribute("id", num);
refreshFileList(files[i].getAbsolutePath(),first1);}
else
{
first1=first.addElement("first1");
String num=String.valueOf(i+1);
first1.addAttribute("name", files[i].getName());
first1.addAttribute("id", num);
refreshFileList(files[i].getAbsolutePath(),first1);
//continue;
}
}
else
continue;
}
}
public static void writeXml(String path,String rootName,String xmlPath) throws IOException
{
//根节点元素
Element root=DocumentHelper.createElement(rootName);
Document document=DocumentHelper.createDocument(root);
refreshFileList(path,root);
//输出到命令行
XMLWriter writer=new XMLWriter();
writer.write(document);
//写在硬盘里
OutputFormat format=new OutputFormat(" ",true);
XMLWriter writer2=new XMLWriter(new FileOutputStream(new File(xmlPath)),format);
writer2.write(document);
}
}