各位有个问题要请教:在一个文件夹下面有许多的文件,比如有a.txt,b.txt,c.txt,d.txt四个文件,我要取得每个特定文件的路径名字,就是把包含a字段的检索出来把它的路径存在String aa中,其他的三个同样存在String bb,cc,dd中,有什么方法可以实现吗?曾想用getCanonicalPath()的indexof于是如下:
 if (f.isDirectory())
   {            
       FindFiles(new String[]{f.getCanonicalPath()});
    }
 else
    {
          String str1="";
          String str2="";
          String str3="";
          String str4="";
         if (f.getCanonicalPath().indexOf("a") != -1)
         {
           str1= f.getCanonicalPath(); 
          }
          if (f.getCanonicalPath().indexOf("b") != -1)
         {
           str2= f.getCanonicalPath(); 
          }
          if (f.getCanonicalPath().indexOf("c") != -1)
         {
           str3= f.getCanonicalPath(); 
          }
          if (f.getCanonicalPath().indexOf("d") != -1)
         {
           str4= f.getCanonicalPath(); 
          }         /**
          *   此处需要调用别的类
          *   参数是str1,str2,str3,str4
          */
    }
但是它的实现方式与预想的不一样,它先是把a.txt按几个if语句遍历一遍,结果只有str1得到赋值,其他三个都为空,然后再把b.txt,c.txt,d.txt遍历,同样只把一个赋值,我想要的是,把四个txt文本分别检索出来,分别得到他们的路径,存到指定的字符串中,请问怎么实现?新手正在学习java,拜托各位!不知道我叙述的清不清楚?

解决方案 »

  1.   

    str1 ... str4 都是在方法内部定义的局部对象,呵呵,自然会清空,
    建议
    StringBuffer aa = new StringBuffer();
    StringBuffer bb= new StringBuffer();
    StringBuffer cc= new StringBuffer();
    StringBuffer dd= new StringBuffer();
    public void FindFiles(String[] ){
      将str = ... 改为
       aa.append(..);} 
    最后再aa.toString()就行了
      

  2.   

    这样明白了,自己扩展一下吧public class myClass {
    StringBuffer sb = new StringBuffer();
    /**遍历目录进行查找包含a的目录*/
    public void findFiles(File file){
       if(file.isDirectory){
           File[] files = file.listFiles();
           for(int i=0;i<files.length;i++){
               findFiles(files[i]);
           }
       }else{
           if(file.getCanonicalPath().indexOf("a") != -1){
               sb.append(file.getCannoicalPath());
               sb.append(" ");
           }
       } }
     /**返回包含a的目录列表,用空格分隔*/
     public String getAPathList(){
        return sb.toString();
     }}
    }
      

  3.   

    谢谢上面这位了,可是它的类型变成了StringBuffer,那么我所使用的类里面参数类型还得修改对不对啊
      

  4.   

    如果不用StringBuffer,你就改为
    StringBuffer sb = new StringBuffer(); 
    -> String str = ""; sb.append(file.getCannoicalPath());
     sb.append(" ");修改为: str += file.getCannocialPath()+" ";return sb.toString() 修改为 return str
      

  5.   

    原来是这样的:类myclass下面有一个方法myfile(string filename)
    FileInputStream in = new FileInputStream( fileName );
    通过myclass的一个对象mc,调用mc.myfile(str1)
    可是str1类型要是换成了stringbuffer方法应该是myfile(stringbuffer filename)
    后面应该怎么使用filename啊?
      

  6.   

    我知道为什么错了,这个else下面的f已经是一个文件了,它必须按照else下面遍历一遍,所以和a,b,c,d,的父文件夹(名字为file)没有关系,那么各位有没有办法在file文件夹下找到这四个文件,并且把各自的路径名传给字符串,str1,str2,str3,str4?