package com.xmgj.jjt.util;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* 读取本地文件中的所有文件目录结构及文件大小
*
* @author Administrator
*
*/
public class XMLtest extends Thread {
@Override
public void run() {
try {
Long start = System.currentTimeMillis();
String name = Thread.currentThread().getName();
System.err.println("当前线程名:" + name);
File file = new File("D:\\jjt-front\\jw\\jw\\jw-web\\src\\main");
Document doc = DocumentHelper.createDocument();
Element el = doc.addElement(file.getName());
el = getFile(file, el);
File docFile = new File("d:" + "/目录结构.xml");
if (!docFile.exists()) {
docFile.createNewFile();
FileOutputStream fos = new FileOutputStream(docFile);
fos.write(doc.asXML().getBytes());
fos.flush();
fos.close();
}
Long end = System.currentTimeMillis();
System.out.println("目录建立成功! 耗时:" + (end - start) + "ms");
} catch (Exception e) {
System.err.println("异常" + e);
}
}
public static Element getFile(File file, Element el) {
try {
File[] list = file.listFiles();
if (list != null && list.length > 0) {
for (File f : list) {
if (f.isDirectory()) {// 目录
Element e = el.addElement("Folder");
e.addAttribute("name", f.getName());
e.addAttribute("lastModify",
parseDate(f.lastModified()));
getFile(f, e);
} else {// 文件
Element e = el.addElement("File");
e.addAttribute("name", f.getName());
e.addAttribute("lastModify",
parseDate(f.lastModified()));
e.addAttribute("size", parseSize(f.length()));
}
System.out.println(el.asXML());
}
}
return el;
} catch (Exception e) {
System.err.println("异常" + e);
}
return null;
}
public static String parseSize(Long l) {
String strSize = "0";
if (l < 1000) {
strSize = l + "B";
} else if (l < 1000 * 1000) {
strSize = l / 1000 + "." + l % 1000 + "K";
} else if (l < 1000 * 1000 * 1000) {
strSize = l / (1000 * 1000) + "." + l % (1000 * 1000) + "M";
} else if (l < 1000 * 1000 * 1000 * 1000) {
strSize = l / (1000 * 1000 * 1000) + "." + l % (1000 * 1000 * 1000)
+ "G";
}
return strSize;
}
public static String parseDate(Long l) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(l);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
return sdf.format(calendar.getTime());
}
public static void main(String[] args) {
try {
File[] file = File.listRoots();
for (File f : file) {
XMLtest tr = new XMLtest();
tr.setName(f.getName());
tr.setPriority(MAX_PRIORITY);
tr.start();
}
} catch (Exception e) {
System.err.println("异常" + e);
}
}
}