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 閱讀(577)
評論(0) 編輯 收藏