java实现文件搜索主要使用file类和正则表达式,如配没下示例:
package com.kiritor.utilimport java.io.File
import java.io.FileFilter
import java.util.Arrays
import java.util.Collections
import java.util.List
/**
* 文件的相关 *** 作类
*
* @author Kiritor
*/
public class FileOperation {
private static String contentPath
private static String filePath
private static File[] fileList = null// 保存文件列表,过滤掉目录
public FileOperation() {
}
/** 构造函数的参数是一个目录 */
public FileOperation(String path) {
File file = new File(path)
if (file.isDirectory())
this.contentPath = path
else
this.filePath = path
}
/**获取文件列表*/
public static File[] getFiles() {
if (contentPath == null) {
File file = new File(filePath)
fileList = new File[1]
fileList[0] = file
return fileList
}
fileList = new 悉橡File(contentPath).listFiles(new FileFilter() {
/**使用过滤器过滤掉目录*/
@Override
public boolean accept(File pathname) {
if(pathname.isDirectory())
{
return false
}else
return true
}
})
return fileList
}
/** 对当前目录下的所有文件进行排序 */
public static File[] sort() {
getFiles()
Arrays.sort(fileList, new FileComparator())
return fileList
}
public static void tree(File f, int level) {
String preStr = ""
for(int i=0 i<level i++) {
preStr += " "
}
File[] childs = f.listFiles()
//返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。
for(int i=0 i<childs.length i++) {
System.out.println(preStr + childs[i].getName())
if(childs[i].isDirectory()) {
tree(childs[i], level + 1)
}
}
}
// 提供一个"比较器"
static class FileComparator implements java.util.Comparator<File> {
@Override
public int compare(File o1, File o2) 睁卖旁{
// 按照文件名的字典顺序进行比较
return o1.getName().compareTo(o2.getName())
}
}
}
要养成看API文档的好习惯。查看API可以看出,
File对象的 String[] list()方法:
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
意思很明确,返回实例化File时,传入的字符串类型的路径名称,此方法返回此路径下的所有文件及目录,不带路径,
File对象的 String[] listFiles()方法:
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
意思很缓桥明确,返回实例化File时,传入的抽象字符串类型的路径名称,此方法返回此路径下的所有文郑局件及目录,含抽象路径.
一般调用System.out.println(Object obj)这个方法,查看Api文档,
System.out返回一个标准的PrintWriter,此PrintWriter是OutputStream的子类,当调用println()方法输出对象时,调用的是对象的toString()方法,如果对象没有覆写toString()方法,则直接输出对象的堆内存地址。
查看API文档,File类的toString()
Returns the pathname string of this abstract pathname
意即返回实例化File对象时候传入的抽象路径
你的test方法,实例化File对象的时候,用的是list()方法得到的,此时本身该抽象路径就只含有文件名而没有喊哪让路径了,另外一个方法则是用的是listFiles()方法,此时得到的都含有抽象路径。因此你输出的时候,就出现这种情况.
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)