java 文件搜索程序

java 文件搜索程序,第1张

import java.io.File

import java.io.FileFilter

public class SearchFile {

private static final class OnlyFile implements FileFilter {

public boolean accept(File pathname) {

if (pathname.isFile()) {

return true

} else {

return false

}

}

}

public static void main(String[] args) {

if (args.length != 2) {

System.out.println("使用说明:请输入java SearchFile 目录 文件名")

} else {

File file = new File(args[0])

File[] files = file.listFiles(new OnlyFile())

for (File f : files) {

if (f.getName().contains(args[1])) {

System.out.println(f.getPath())

}

}

}

}

}

//注意路径名不能有空格

 

 

你必须用 File 类(http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/io/File.html)。

写了个简单的例子让你参考:

import java.io.*

import java.util.*

class SimpleLocalDriveSearch {

    private List result = new ArrayList( )

    private void recursiveSearch( File rootDir, String suffix ) {

        File[ ] files = rootDir.listFiles( )

        if ( files != null )

            for ( int i = 0i <files.lengthi++ ) {

                if ( files[ i ].isFile( ) &&files[ i ].getName( ).endsWith( suffix ) )

                    result.add( files[ i ] )

                recursiveSearch( files[ i ], suffix )

            }

    }

    public List search( File startDir, String matchingExtension ) {

        result.clear( )

        recursiveSearch( startDir, "." + matchingExtension )

        return result

    }

    public static void main( String[ ] args ) throws Exception {

        System.out.println( "Enter the extension of files to be searched for:" )

        String ext = new BufferedReader( new InputStreamReader( System.in ) ).readLine( )

        SimpleLocalDriveSearch slds = new SimpleLocalDriveSearch( )

        File[ ] roots = File.listRoots( )

        for ( int i = 0i <roots.lengthi++ ) {

            List found = slds.search( roots[ i ], ext )

            if ( found.size( ) >0 )

                for ( Iterator iter = found.iterator( )iter.hasNext( ))

                    System.out.println( iter.next( ) )

            else

                System.out.println( "No match on " + roots[ i ] )

        }

    }

}

 

 

 


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11884634.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存