下面列出了怎么用java.io.FileFilter的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean isProtosAvailable(String fileLocation) {
File file = new File(fileLocation);
if (!file.exists()) {
return false;
}
FilenameFilter protoFilter = (f, name) -> (name.endsWith(".proto"));
String[] fileNames = file.list(protoFilter);
if (fileNames != null && fileNames.length > 0) {
return true;
}
//allow the users to have proto definitions inside a directory if required
FileFilter dirFilter = (f) -> f.isDirectory();
File[] subDirectories = file.listFiles(dirFilter);
for (File dir : subDirectories) {
return isProtosAvailable(dir.getAbsolutePath());
}
return false;
}
private Map<File, List<File>> recoverIndexDirectories() {
final Map<File, List<File>> indexDirectoryMap = new HashMap<>();
for (final File storageDirectory : repoConfig.getStorageDirectories().values()) {
final List<File> indexDirectories = new ArrayList<>();
final File[] matching = storageDirectory.listFiles(new FileFilter() {
@Override
public boolean accept(final File pathname) {
return pathname.isDirectory() && indexNamePattern.matcher(pathname.getName()).matches();
}
});
if (matching != null) {
for (final File matchingFile : matching) {
indexDirectories.add(matchingFile);
}
}
indexDirectoryMap.put(storageDirectory, indexDirectories);
}
return indexDirectoryMap;
}
/**
* Return the files that satisfy the filter in directory.
*
* @param dir The directory.
* @param filter The filter.
* @param isRecursive True to traverse subdirectories, false otherwise.
* @return the files that satisfy the filter in directory
*/
public static List<File> listFilesInDirWithFilter(final File dir, final FileFilter filter,
final boolean isRecursive) {
if (!isDir(dir)) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file)) {
list.add(file);
}
if (isRecursive && file.isDirectory()) {
//noinspection ConstantConditions
list.addAll(listFilesInDirWithFilter(file, filter, true));
}
}
}
return list;
}
/**
* <p>Determine whether a file is to be accepted or not, based on the
* contained filters. The file is accepted if any one of the contained
* filters accepts it. This method stops looping over the contained
* filters as soon as it encounters one whose <tt>accept()</tt> method
* returns <tt>false</tt> (implementing a "short-circuited AND"
* operation.)</p>
*
* <p>If the set of contained filters is empty, then this method
* returns <tt>true</tt>.</p>
*
* @param file The file to check for acceptance
*
* @return <tt>true</tt> if the file matches, <tt>false</tt> if it doesn't
*/
public boolean accept (File file)
{
boolean accepted = false;
if (filters.size() == 0)
accepted = true;
else
{
for (FileFilter filter : filters)
{
accepted = filter.accept (file);
if (accepted)
break;
}
}
return accepted;
}
/**
* 删除遗留的低版本的apk
*/
private static void deleteOldApks(File rootDir, final String packageName) {
List<File> apkFiles = new ArrayList<>();
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName();
return name.startsWith(packageName) && name.endsWith(APK_SUFFIX);
}
};
File[] files = rootDir.listFiles(fileFilter);
if (files != null) {
for (File file : files) {
apkFiles.add(file);
}
}
// 删除相关apk文件
for (File apkFile : apkFiles) {
if (apkFile.delete()) {
PluginDebugLog.installFormatLog(TAG, "deleteOldApks %s, dex %s success!", packageName, apkFile.getAbsolutePath());
} else {
PluginDebugLog.installFormatLog(TAG, "deleteOldApks %s, dex %s fail!", packageName, apkFile.getAbsolutePath());
}
}
}
/**
* Gets the number of cores available in this device, across all processors.
* Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
* @return The number of cores, or 1 if failed to get result
*/
private int getNumCoresOldPhones() {
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return Pattern.matches("cpu[0-9]+", pathname.getName());
}
}
try {
File dir = new File("/sys/devices/system/cpu/");
File[] files = dir.listFiles(new CpuFilter());
return files.length;
} catch(Exception e) {
return 1;
}
}
/**
* Delete all files that satisfy the filter in directory.
*
* @param dir The directory.
* @param filter The filter.
* @return {@code true}: success<br>{@code false}: fail
*/
public static boolean deleteFilesInDirWithFilter(final File dir, final FileFilter filter) {
if (dir == null) return false;
// dir doesn't exist then return true
if (!dir.exists()) return true;
// dir isn't a directory then return false
if (!dir.isDirectory()) return false;
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file)) {
if (file.isFile()) {
if (!file.delete()) return false;
} else if (file.isDirectory()) {
if (!deleteDir(file)) return false;
}
}
}
}
return true;
}
@Override
public List<File> findFiles(final File directoryToSearch, final List<String> filenamePatterns, final int depth, boolean findInsideMatchingDirectories) {
List<File> found = new ArrayList<>();
for (int i = 0; i <= depth; i++) {
if (files.containsKey(i)) {
List<File> possibles = files.get(i);
for (String pattern : filenamePatterns) {
FileFilter fileFilter = new WildcardFileFilter(pattern);
for (File possible : possibles) {
if (fileFilter.accept(possible)) {
found.add(possible);
}
}
}
}
}
return found;
}
/**
* 获取CPU个数
*/
public static int getCoreNum() {
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
// Check if filename is "cpu", followed by a single digit number
if (Pattern.matches("cpu[0-9]", pathname.getName())) {
return true;
}
return false;
}
}
try {
// Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
// Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
// Return the number of cores (virtual CPU devices)
return files.length;
} catch (Exception e) {
Log.e(TAG, "getCoreNum", e);
// Default to return 1 core
return 1;
}
}
/**
* 查找该目录下的所有的jar文件
*
* @param jarPath
* @throws Exception
*/
private String getJarFiles(String jarPath) throws Exception {
File sourceFile = new File(jarPath);
// String jars="";
if (sourceFile.exists()) {// 文件或者目录必须存在
if (sourceFile.isDirectory()) {// 若file对象为目录
// 得到该目录下以.java结尾的文件或者目录
File[] childrenFiles = sourceFile.listFiles(new FileFilter() {
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
} else {
String name = pathname.getName();
if (name.endsWith(".jar") ? true : false) {
jars = jars + pathname.getPath() + File.separatorChar;
return true;
}
return false;
}
}
});
}
}
return jars;
}
/**
* 递归遍历所有文件
*/
public static List<File> listAllFiles(File dir, FileFilter filter) {
List<File> result = new ArrayList<>();
LinkedList<File> dirs = new LinkedList<>();
dirs.add( dir );
while(!dirs.isEmpty()) {
File file = dirs.poll();
if ( file.isDirectory() ) {
File[] files = file.listFiles();
if (files!=null) {
dirs.addAll(Arrays.asList(files));
}
continue;
}
if ( filter==null || filter.accept(file) ) {
result.add(file);
}
}
return result;
}
private Map<String, File[]> getCachedTableSnapshotsFolders(File dbBaseFolder) {
Map<String, File[]> result = Maps.newHashMap();
File[] tableFolders = dbBaseFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory();
}
});
if (tableFolders == null) {
return result;
}
for (File tableFolder : tableFolders) {
String tableName = tableFolder.getName();
File[] snapshotFolders = tableFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File snapshotFile) {
return snapshotFile.isDirectory();
}
});
result.put(tableName, snapshotFolders);
}
return result;
}
/**
* 获取目录下所有过滤的文件
* @param dir 目录
* @param filter 过滤器
* @param isRecursive 是否递归进子目录
* @return 文件链表
*/
public static List<FileList> listFilesInDirWithFilterBean(final File dir, final FileFilter filter, final boolean isRecursive) {
if (!isDirectory(dir) || filter == null) return null;
List<FileList> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file)) {
FileList fileList;
if (isRecursive && file.isDirectory()) {
List<FileList> subs = listFilesInDirWithFilterBean(file, filter, true);
fileList = new FileList(file, subs);
} else {
fileList = new FileList(file);
}
list.add(fileList);
}
}
}
return list;
}
public LoadLevelWindow(SideScroller a, GameplayScene scene) {
super(a);
collidableObjects = new ArrayList<CollidableObject>();
backgroundObjects = new ArrayList<BackgroundObject>();
picked = "";
this.scene = scene;
f = new File(path);
f.mkdirs();
File[] files = f.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return name.endsWith(".dat") && pathname.isFile();
}
});
list = new List(a, Arrays.stream(files).map(File::getName).toArray(String[]::new), 30);
list.setSizeH(200);
list.setPosition(applet.width / 2 + 400, 325);
list.setConfirmButton("Confirm", applet.width / 2 + 400, 500);
list.setCancelButton("Cancel", applet.width / 2 + 400, 550);
}
/**
* Finds files within a given directory (and optionally its
* subdirectories). All files found are filtered by an IOFileFilter.
*
* @param files the collection of files found.
* @param directory the directory to search in.
* @param filter the filter to apply to files and directories.
* @param includeSubDirectories indicates if will include the subdirectories themselves
*/
private static void innerListFiles(Collection<File> files, File directory,
IOFileFilter filter, boolean includeSubDirectories) {
File[] found = directory.listFiles((FileFilter) filter);
if (found != null) {
for (File file : found) {
if (file.isDirectory()) {
if (includeSubDirectories) {
files.add(file);
}
innerListFiles(files, file, filter, includeSubDirectories);
} else {
files.add(file);
}
}
}
}
public BreadthFirstDirectoryVisitor(Iterable<File> startingDirectories,
final FileFilter directoryFilter, FileFilter filter,
boolean compareCase) {
this.directoryFilter = directoryFilter == null ? DIRECTORIES
: new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory()
&& directoryFilter.accept(pathname);
}
};
this.filter = filter;
comparator = compareCase ? CASE_SENSITIVE : CASE_INSENSITIVE;
for (File directory : startingDirectories) {
if (!directory.isDirectory()) {
throw new RuntimeException(directory + " is not a directory");
}
directoryQueue.addLast(directory);
}
}
private void copyImagesAndCertificates(String origConfigFile, TestContext context) {
File sourceDir = new File(origConfigFile).getParentFile();
if(!sourceDir.exists()) {
sourceDir = new File(ImportTestAction.class.getResource(origConfigFile).getFile()).getParentFile();
if(!sourceDir.exists()) {
return;
}
}
FileFilter filter = new WildcardFileFilter(new String[] {"*.crt", "*.jpg", "*.png", "*.pem"});
try {
LOG.info("Copy certificates and images from source: "+sourceDir+" into test-dir: '"+testDir+"'");
FileUtils.copyDirectory(sourceDir, testDir, filter);
} catch (IOException e) {
}
}
/**
* 删除目录下所有过滤的文件
* @param dir 目录
* @param filter 过滤器
* @return {@code true} 删除成功, {@code false} 删除失败
*/
public static boolean deleteFilesInDirWithFilter(final File dir, final FileFilter filter) {
if (filter == null) return false;
// dir is null then return false
if (dir == null) return false;
// dir doesn't exist then return true
if (!dir.exists()) return true;
// dir isn't a directory then return false
if (!dir.isDirectory()) return false;
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
if (filter.accept(file)) {
if (file.isFile()) {
if (!file.delete()) return false;
} else if (file.isDirectory()) {
if (!deleteDir(file)) return false;
}
}
}
}
return true;
}
static FileFilter createFilter(final String extension) {
return new FileFilter() {
@Override
public boolean accept(File pathname) {
String name = pathname.getName();
if (name.endsWith(extension)) {
return true;
}
return false;
}
};
}
@Parameterized.Parameters(name = "{0}")
public static List<Object[]> getTestParameters() {
FileFilter ff = new NotFileFilter(new SuffixFileFilter(".cdl"));
List<Object[]> result = new ArrayList<Object[]>(500);
try {
TestDir.actOnAllParameterized(TestDir.cdmUnitTestDir + "formats/netcdf3/", ff, result);
TestDir.actOnAllParameterized(TestDir.cdmUnitTestDir + "formats/netcdf4/", ff, result);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static List<File> listFiles(File dir, FileFilter filter)
{
File[] files = dir.listFiles(filter);
if (files == null) {
return ImmutableList.of();
}
return ImmutableList.copyOf(files);
}
/**
* Search files from specified file path
* @param filesPath filepath be searched
* @param query search key word
* @return search result
*/
public static List<FileEntity> searchFiles(String filesPath, final String query) {
File file = new File(filesPath);
if (!file.exists()) {
file.mkdirs();
return new ArrayList<>();
}
final ArrayList<FileEntity> entityList = new ArrayList<>();
file.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
boolean isAccept;
String fileName = pathname.getName();
isAccept = fileName.contains(query) && (fileName.endsWith(".md")
|| fileName.endsWith(".markdown") || fileName.endsWith(".mdown"));
if (isAccept) {
FileEntity entity = new FileEntity();
entity.setName(pathname.getName());
entity.setLastModified(pathname.lastModified());
entity.setAbsolutePath(pathname.getAbsolutePath());
entityList.add(entity);
}
return isAccept;
}
});
Collections.sort(entityList, new Comparator<FileEntity>() {
@Override
public int compare(FileEntity o1, FileEntity o2) {
return Long.compare(o2.getLastModified(), o1.getLastModified());
}
});
return entityList;
}
public List<File> getFilesInSortedOrder(Path dirPath) {
File[] files = dirPath.toFile().listFiles((FileFilter) FileFileFilter.FILE);
// Sort the file first by last_modified timestamp and then by name in case two files have
// the same mtime due to precision (mtime is up to seconds).
Ordering<File> ordering = Ordering.from(new SingerUtils.LogFileComparator());
List<File> logFiles = ordering.sortedCopy(Arrays.asList(files));
return logFiles;
}
/**
* 刷新文件夹记录
*/
private void refreshRecords() {
if (recordDir != null && recordDir.exists() && recordDir.isDirectory()) {
// 记录所有相关文件夹
File[] list = recordDir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() && (newPattern.matcher(file.getName()).matches() || midPattern.matcher(file.getName()).matches() || oldPattern.matcher(file.getName()).matches());
}
});
LogUtil.i(TAG, "get files " + StringUtil.hide(list));
// 修改顺序排序
Arrays.sort(list, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return Long.valueOf(o2.lastModified()).compareTo(o1.lastModified());
}
});
recordFolderNames.clear();
for (File f: list) {
recordFolderNames.add(f.getName());
}
LogUtil.i(TAG, "get folders: " + recordFolderNames.size());
}
}
private File[] getResources() {
try {
File file = new File(classLoader.getResource(CAL_PRICE_PACKAGE.replace(".", "/")).toURI());
return file.listFiles(new FileFilter() {
public boolean accept(File pathname) {
if (pathname.getName().endsWith(".class")) {//我们只扫描class文件
return true;
}
return false;
}
});
} catch (URISyntaxException e) {
throw new RuntimeException("未找到策略资源");
}
}
@Nullable
private static String getTargetJar(String project, String classifier) {
File agentBuildDir = new File("../../" + project + "/target/");
FileFilter fileFilter = file -> file.getName().matches(project + "-\\d\\.\\d+\\.\\d+(-SNAPSHOT)?" + classifier + ".jar");
return Arrays.stream(agentBuildDir.listFiles(fileFilter)).findFirst()
.map(File::getAbsolutePath)
.orElse(null);
}
/**
* Loads all profiles from the specified directory.
*
* Do not use this method for files distributed within a jar.
*
* @param path profile directory path
* @return empty if there is no language file in it.
*/
public List<LanguageProfile> readAll(File path) throws IOException {
if (!path.exists()) {
throw new IOException("No such folder: " + path);
}
if (!path.canRead()) {
throw new IOException("Folder not readable: " + path);
}
File[] listFiles = path.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return looksLikeLanguageProfileFile(pathname);
}
});
if (listFiles == null) {
throw new IOException("Failed reading from folder: " + path);
}
List<LanguageProfile> profiles = new ArrayList<>(listFiles.length);
for (File file : listFiles) {
if (!looksLikeLanguageProfileFile(file)) {
continue;
}
profiles.add(read(file));
}
return profiles;
}
/**
* 查找该目录下的所有的java文件
*
* @param sourceFile
* @param sourceFileList
* @throws Exception
*/
private void getSourceFiles(File sourceFile, List<File> sourceFileList) throws Exception {
if (sourceFile.exists() && sourceFileList != null) {//文件或者目录必须存在
if (sourceFile.isDirectory()) {// 若file对象为目录
// 得到该目录下以.java结尾的文件或者目录
File[] childrenFiles = sourceFile.listFiles(new FileFilter() {
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
} else {
String name = pathname.getName();
if (name.endsWith(".java") ? true : false) {
return true;
}
return false;
}
}
});
// 递归调用
for (File childFile : childrenFiles) {
getSourceFiles(childFile, sourceFileList);
}
} else {// 若file对象为文件
sourceFileList.add(sourceFile);
}
}
}
/**
* 获取 CPU 核心数
* @return CPU 核心数
*/
public static int getCoresNumbers() {
// Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
// Check if filename is "cpu", followed by a single digit number
return Pattern.matches("cpu[0-9]+", pathname.getName());
}
}
// CPU 核心数
int CPU_CORES = 0;
try {
// Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
// Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
// Return the number of cores (virtual CPU devices)
CPU_CORES = files.length;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "getCoresNumbers");
}
if (CPU_CORES < 1) {
CPU_CORES = Runtime.getRuntime().availableProcessors();
}
if (CPU_CORES < 1) {
CPU_CORES = 1;
}
return CPU_CORES;
}
public PathAdapter(List<File> mListData, Context mContext, FileFilter mFileFilter, boolean mMutilyMode, boolean mIsGreater, long mFileSize) {
this.mListData = mListData;
this.mContext = mContext;
this.mFileFilter = mFileFilter;
this.mMutilyMode = mMutilyMode;
this.mIsGreater = mIsGreater;
this.mFileSize = mFileSize;
mCheckedFlags = new boolean[mListData.size()];
}