递归生成目录文件列表

很早前在学校时候写的一个生成目录文件列表的东西,因为那时候自己开了一个ftp服务器。

import java.util.Date;
import java.util.Arrays;
import java.io.*;

/**
* Time: 2003-12-23 20:46:42
*/
public class FileManager {
private String ListFilename = "@list.txt";
private String root;
private String updatetime;

public FileManager(String root) {
this.root = root;
updatetime=new Date().toString();
}


private void getList(String dir) {
File tmp = new File(dir);
File[] files = tmp.listFiles(new ffilter());
File[] dirs = tmp.listFiles(new dfilter());

if (files.length != 0) {
writeListFile(files);
}
if (dirs.length != 0) {
for (int i = 0; i < dirs.length; i++)
getList(tmp.getPath() + "/" + dirs[i].getName());
}
}

private void writeListFile(File[] files) {
FileWriter f = null;
String parent = files[0].getParent();
try {
int size;
f = new FileWriter(parent +"/"+ListFilename);
f.write("【列表最后更新时间】"+" :"+updatetime);
f.write(13);
f.write(10);
f.write("【欢迎分享我的收藏】,enjoy!");
f.write(13);
f.write(10);

//排列顺序
Arrays.sort(files);
for (int i = 0; i < files.length; i++) {
f.write(files[i].getName());
size = ((int) files[i].length()) ;
f.write(" 【size:"+size/1000+"k】");
f.write(13);
f.write(10);
}
f.flush();
f.close();
} catch (FileNotFoundException e) {
System.out.println("file not found");
} catch (IOException e) {
}
}

public void run() {
delete(root);
getList(root);
}

private void delete(String dir) {
File tmp = new File(dir);
File lfile = new File(dir + "/" + ListFilename);
lfile.delete();
File[] dirs = tmp.listFiles(new dfilter());

if (dirs.length != 0) {
for (int i = 0; i < dirs.length; i++)
delete(tmp.getPath() + "/" + dirs[i].getName());
}

}

public static void main(String args[]) {
/*      String dowhat = "list";
if (args[0] != null) Root = args[0];
if (args[1] != null) dowhat = args[1];
FileManager f = new FileManager(Root);
if (args[1] == "list")
f.getList(Root);
else if (args[1] == "delete") f.delete(Root);*/

FileManager f=new FileManager(args[0]);
f.run();
}
}

class ffilter implements FileFilter {
public boolean accept(File pathname) {
String name = pathname.getName();
return (pathname.isFile()) && (name.indexOf(".mp3") != -1);
}
}

class dfilter implements FileFilter {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
}

Comments are closed.