<!--
Author:Lovingshu
Date:2012/03/12 19:04
Remark:The methods to get all the files and folders that you want!I just want to say:the thread in java is so wonder
twice better than it in C#,The biggest headache in C# is that you can't invoke the methods in the thread!But Java
in Java you can do anything!But I heard that thread in new version C# support invoke the methods~but I don't try!
So guys~,have a nice day!I must prepared well for the interview of BeiJing!
-->
//those variable must be static or will lead to null pointer
//use it to know the file's path
private static String filePath;
//these two thread has their own duty~
private static Thread thOne=null;
private static Thread thTwo=null;
//inner class use it to find the files and folders
class ThreadOne extends Thread{
@Override
public void run() {
long begin=System.currentTimeMillis();
String allFile=getFiles(filePath,0);
try {
FileWriter fw=new FileWriter("E:\\Directory Informations.txt");
fw.write(allFile);
fw.close();
System.out.println("job is done~!");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("totally:"+(System.currentTimeMillis()-begin));
//this method is already passed~but interrupt is not ok~
thTwo.stop();
//remember to interrupt the thread
thOne.interrupt();
}
//the method to find the files
public String getFiles(String path,int ins){
String allContent="";
File file=new File(path);
if(!file.exists()){
return "Sorry~The File Is Not Exists~Please Enter The Correct Path!";
}
File[] files=file.listFiles();
for(File fi : files){
try{
if(fi.isFile()){
for(int i=0;i<ins-1;i++){
allContent+="\t";
}
allContent+=" -"+fi.getName()+"kb\r\n";
}else{
for(int i=0;i<ins;i++){
allContent+="\t";
}
allContent+="["+fi.getName()+"]\r\n";
//if it is folder add one indentation
ins++;
//and recursive calls
allContent+=getFiles(fi.getPath(),ins)+"\r\n";
//after finish recursive calls remember to decrease the indentation
ins--;
}
}catch(Exception e){
//when face some folder that you can't get in~
allContent+="\r\n####################################################################\r\n";
allContent+="When get file :<"+fi.getName()+"> errors happend~";
allContent+="\r\n####################################################################\r\n";
continue;
}
}
return allContent;
}
}
//the counter
class ThreadTwo extends Thread{
@Override
public void run() {
System.out.println("File Checking On ["+filePath+"] Is Starting~Plase Wait~");
int i=0;
while(1==1){
i++;
System.out.println(i+" seconds passed");
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
System.out.println("Please Enter The Path That You Wanna Check:");
new BaseDAO().getStarted(new Scanner(System.in).nextLine());
}
public void getStarted(String path){
filePath=path;
thOne=new BaseDAO().new ThreadOne();
thOne.start();
thTwo=new BaseDAO().new ThreadTwo();
thTwo.start();
}
文件查找(双线程优化版)
最新推荐文章于 2024-05-15 21:17:45 发布