2013-03-25 173 views
9

这应该很简单,但我无法得到它 - “编写一个程序,搜索给定目录中的特定文件名。”我发现了一些硬编码文件名和目录的例子,但我需要用户输入的目录和文件名。Java - 在目录中搜索文件

public static void main(String[] args) { 
    String fileName = args[0]; // For the filename declaration 
    String directory;  
    boolean found; 

    File dir = new File(directory); 

    File[] matchingFiles = dir.listFiles(new FilenameFilter() { 
     public boolean accept(File dir, String fileName) { 
      return true; 
     } 
    }); 

} 
+3

这可不行,因为在“返回文件名”编译时错误。改变它返回true,它将返回所有文件。也请看http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles() – 2013-03-25 20:36:26

+0

您的问题是什么? – 2013-03-25 20:37:45

回答

23

你可以尝试这样的事:

import java.io.*; 
import java.util.*; 
class FindFile 
{ 
    public void findFile(String name,File file) 
    { 
     File[] list = file.listFiles(); 
     if(list!=null) 
     for (File fil : list) 
     { 
      if (fil.isDirectory()) 
      { 
       findFile(name,fil); 
      } 
      else if (name.equalsIgnoreCase(fil.getName())) 
      { 
       System.out.println(fil.getParentFile()); 
      } 
     } 
    } 
    public static void main(String[] args) 
    { 
     FindFile ff = new FindFile(); 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Enter the file to be searched.. "); 
     String name = scan.next(); 
     System.out.println("Enter the directory where to search "); 
     String directory = scan.next(); 
     ff.findFile(name,new File(directory)); 
    } 
} 

这里是输出:

J:\Java\misc\load>java FindFile 
Enter the file to be searched.. 
FindFile.java 
Enter the directory where to search 
j:\java\ 
FindFile.java Found in->j:\java\misc\load 
+0

嗨@Vishal,这段代码不帮我从用户那里得到目录和文件名,这是问题所在。 – 2013-03-25 20:50:11

+0

此代码给出了文件所在目录的完整路径。运行此代码..在'main'方法中更改find​​File的参数。 – 2013-03-25 20:52:15

+1

@AC查看最新的代码.. – 2013-03-25 20:57:36

1

这看起来像一个家庭作业的问题,所以我只给你几个指针:

尽量给好独特的变量名。在这里,您先使用“fileName”作为目录,然后使用该文件。这是令人困惑的,并不会帮助你解决问题。为不同的事物使用不同的名字。

您没有使用Scanner进行任何操作,在此不需要它,请将其除去。

此外,accept方法应该返回一个布尔值。现在,你正试图返回一个字符串。布尔意味着它应该返回true或false。例如,return a > 0;可能会返回true或false,具体取决于a的值。但return fileName;将只返回fileName的值,这是一个字符串。

1

如果要使用动态文件名过滤器可以实现的FilenameFilter,并通过在构造函数中动态名称。

当然这一点意味着taht必须实例每次类(开销),但它的作品

例子:

public class DynamicFileNameFilter implements FilenameFilter { 

    private String comparingname; 

    public DynamicFileNameFilter(String comparingName){ 
     this.comparingname = comparingName; 
    } 

    @Override 
    public boolean accept(File dir, String name) { 
     File file = new File(name); 

     if (name.equals(comparingname) && !file.isDirectory()) 
      return false; 

     else 
      return true; 
    } 

} 

然后你使用,你需要:

FilenameFilter fileNameFilter = new DynamicFileNameFilter("thedynamicNameorpatternYouAreSearchinfor"); 
File[] matchingFiles = dir.listFiles(fileNameFilter); 
+0

你确定'file = new File(name)':这将从一个简单的名字构建一个文件,它不属于walked目录。所以'file.isDirectory()'可能会给你意想不到的结果。我会用'新的文件(名字,目录)'去 – GPI 2014-08-06 21:07:07

0

我使用了不同的方法来使用堆栈搜索文件。请记住,文件夹内可能存在文件夹。虽然它不比windows搜索快(但我并没有期待那样),但它肯定会给出正确的结果。请根据需要修改代码。此代码最初是为了提取某些文件扩展名的文件路径:)。随意优化。

import java.io.File; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 

/** 
* @author Deepankar Sinha 
*/ 
public class GetList { 
    public List<String> stack; 
    static List<String> lnkFile; 
    static List<String> progName; 

    int index=-1; 
    public static void main(String args[]) throws IOException 
    { 

     //var-- progFile:Location of the file to be search. 
     String progFile="C:\\"; 
     GetList obj=new GetList(); 
     String temp=progFile; 
     int i; 
     while(!"&%@#".equals(temp)) 
     { 
      File dir=new File(temp); 
      String[] directory=dir.list(); 
      if(directory!=null){ 
      for(String name: directory) 
      { 
       if(new File(temp+name).isDirectory()) 
        obj.push(temp+name+"\\"); 
       else 
        if(new File(temp+name).isFile()) 
        { 
         try{ 
          //".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:) 
         if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length()))) 
         { 
          //obj.addFile(temp+name,name); 
          System.out.println(temp+name); 
         } 
         }catch(StringIndexOutOfBoundsException e) 
         { 
          //debug purpose 
          System.out.println("ERROR******"+temp+name); 
         } 

        } 
      }} 
      temp=obj.pop(); 
     } 
     obj.display(); 

//  for(int i=0;i<directory.length;i++) 
//  System.out.println(directory[i]); 
    } 

    public GetList() { 
     this.stack = new ArrayList<>(); 
     this.lnkFile=new ArrayList<>(); 
     this.progName=new ArrayList<>(); 
    } 
    public void push(String dir) 
    { 
     index++; 
     //System.out.println("PUSH : "+dir+" "+index); 
     this.stack.add(index,dir); 

    } 
    public String pop() 
    { 
     String dir=""; 
     if(index==-1) 
      return "&%@#"; 
     else 
     { 
      dir=this.stack.get(index); 
      //System.out.println("POP : "+dir+" "+index); 
      index--; 

     } 
     return dir; 
    } 

    public void addFile(String name,String name2) 
    { 
     lnkFile.add(name); 
     progName.add(name2); 
    } 

    public void display() 
    { 
     GetList.lnkFile.stream().forEach((lnkFile1) -> { 
      System.out.println(lnkFile1); 
     }); 
    } 

} 
0

下面的代码有助于搜索文件的目录,并打开它的位置

import java.io.*; 
import java.util.*; 
import java.awt.Desktop; 
public class Filesearch2 { 


    public static void main(String[] args)throws IOException {   
     Filesearch2 fs = new Filesearch2(); 
     Scanner scan = new Scanner(System.in); 
     System.out.println("Enter the file to be searched.. "); 
     String name = scan.next(); 
     System.out.println("Enter the directory where to search "); 
     String directory = scan.next(); 
     fs.findFile(name,new File(directory)); 
    } 
    public void findFile(String name,File file1)throws IOException 
    {  
     File[] list = file1.listFiles();  
     if(list!=null) 
    {       
     for(File file2 : list) 
     {    
      if (file2.isDirectory()) 
      { 
       findFile(name,file2);    
      } 
      else if (name.equalsIgnoreCase(file2.getName())) 
      {                
       System.out.println("Found");     
       System.out.println("File found at : "+file2.getParentFile()); 
       System.out.println("Path diectory: "+file2.getAbsolutePath()); 
       String p1 = ""+file2.getParentFile(); 
       File f2 = new File(p1); 
       Desktop.getDesktop().open(f2);        
      }      
     }   
     } 
    }   
} 
0

有**的Java 8 *有使用流和lambda表达式替代:

public static void recursiveFind(Path path, Consumer<Path> c) { 
    try (DirectoryStream<Path> newDirectoryStream = Files.newDirectoryStream(path)) { 
    StreamSupport.stream(newDirectoryStream.spliterator(), false) 
       .peek(p -> { 
        c.accept(p); 
        if (p.toFile() 
         .isDirectory()) { 
        recursiveFind(p, c); 
        } 
       }) 
       .collect(Collectors.toList()); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 

所以这将递归地打印所有文件:

recursiveFind(Paths.get("."), System.out::println); 

,这将搜索一个文件:

recursiveFind(Paths.get("."), p -> { 
    if (p.toFile().getName().toString().equals("src")) { 
    System.out.println(p); 
    } 
});