import java.io.*;
public class FileRead{
private static double totalFile = 0;
private static double totalDirectory = 0;
public String replace(String value){
StringBuffer replace = new StringBuffer(value);
int i = 0;
int last = replace.lastIndexOf("──");
i = replace.indexOf("──");
while((i != last)&&(i != -1)){
replace.replace(i,i+"──".length()," ");
i = replace.indexOf("──");
last = replace.lastIndexOf("──");
}
return replace.toString();
}
public void searchFile(File f,String value,boolean b)throws IOException{
StringBuffer string = new StringBuffer(value);
string.append("──");
boolean bool = b;
String path = f.getAbsolutePath();
File currentFile = new File(path); //取得当前路径的文件
File[] file = currentFile.listFiles();
for(int i=0;i<file.length;i++){
StringBuffer s = null;
String lastDirectory = null;
/*
* 判断文件夹是否为该目录下的最后一个文件夹,如果是的话,则取消打印"│"符号
*/
for(int k=0;k<file.length;k++){
if(file[k].isDirectory())
lastDirectory = new String(file[k].getName());
}
if(file[i].getName().equals(lastDirectory)){
if(string.indexOf("│") != -1){
string.delete(string.lastIndexOf("│"),string.lastIndexOf("│")+1);
}
}
/*
* 格式化打印,将符号最后的"──"变为"├──"(当最后的符号不为"│──"时)
*/
if(!((string.lastIndexOf("──")-1) == string.lastIndexOf("│──"))){
s = new StringBuffer(string.substring(0,string.lastIndexOf("──")));
s.append("├──");
}else{
if(string.indexOf("│──")!=-1){
s = new StringBuffer(string.substring(0,string.lastIndexOf("│──")));
s.append("├──");
}
}
if(file[i].getName().equals(file[file.length-1].getName()))
if(s != null)
if(s.lastIndexOf("├") != -1)
s.replace(s.lastIndexOf("├"),s.lastIndexOf("├")+1,"└");
/*
* 如果s不为空,则将s传入方法replace中进行格式化
*/
if(s != null)
System.out.println(replace(s.toString()) + file[i].getName());
if(file[i].isDirectory()){
totalDirectory += 1;
/*
* 如果该文件夹的子目录下还有两个以上的文件和文件夹,则打印一个"│"符号,并标记bool为true
*/
String pathstring = file[i].getAbsolutePath();
File current = new File(pathstring); //取得当前路径的文件
File[] fp = current.listFiles();
if(fp.length >1){
bool = true;
}
if(bool)
string.append("│");
searchFile(file[i],string.toString(),bool);
/*
* 如果bool已经被标记过,则将上一次的"│"符号删除
*/
if(bool)
if(string.indexOf("│") != -1)
string.delete(string.lastIndexOf("│"),string.length());
bool = false;
}
totalFile += 1;
}
}
public static void main(String args[])throws IOException{
String path = null;
if(args.length<1)
path =".";
else
path = args[0];
FileRead read = new FileRead();
File file = new File(path);
if(!file.exists()){
System.err.print("the path is error");
System.exit(1);
}
read.searchFile(file,"│",false);
System.out.println("the file is :" + (totalFile-totalDirectory));
System.out.println("thd directory is : " + totalDirectory);
}
}
该程序存在一个问题,也就是当jdk中的File类无法判断目录下的一些目录是文件夹或则是文件时?
posted on 2005-08-19 20:20
sky 阅读(574)
评论(0) 编辑 收藏