java.io.FilenameFilter Java Examples

The following examples show how to use java.io.FilenameFilter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileNavigator.java    From Android-FileBrowser-FilePicker with MIT License 9 votes vote down vote up
public File [] getFilesInCurrentDirectory() {
   if(mAllowedFileExtensionFilter!=null) {
       FilenameFilter fileNameFilter = new FilenameFilter() {
           @Override
           public boolean accept(File dir, String name) {
               File absolutePath = new File(dir, name);
               if (absolutePath.isDirectory()) {
                   return  true;
               }
               String fileExtension = FilenameUtils.getExtension(name);
               if(mAllowedFileExtensionFilter.contains(fileExtension)) {
                   return true;
               }
               return false;
           }
       };
       return mCurrentNode.listFiles(fileNameFilter);
   }
   return mCurrentNode.listFiles();
}
 
Example #2
Source File: LoggingBuilderTest.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public void testDailyRollingFileAppender() throws InterruptedException {
    String rollingFile = loggingDir + "/daily-rolling--222.log";
    Appender rollingFileAppender = LoggingBuilder.newAppenderBuilder().withAsync(false, 1024)
        .withDailyFileRollingAppender(rollingFile, "'.'yyyy-MM-dd_HH-mm-ss-SSS")
        .withLayout(LoggingBuilder.newLayoutBuilder().withDefaultLayout().build()).build();

    for (int i = 0; i < 100; i++) {
        rollingFileAppender.doAppend(loggingEvent);
    }

    rollingFileAppender.close();

    File file = new File(loggingDir);
    String[] list = file.list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith("daily-rolling--222.log");
        }
    });
    Assert.assertTrue(list.length > 0);
}
 
Example #3
Source File: StateConfigRuleSelect.java    From nullpomino with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get rule file list
 * @return Rule file list. null if directory doesn't exist.
 */
private String[] getRuleFileList() {
	File dir = new File("config/rule");

	FilenameFilter filter = new FilenameFilter() {
		public boolean accept(File dir1, String name) {
			return name.endsWith(".rul");
		}
	};

	String[] list = dir.list(filter);

	if(!System.getProperty("os.name").startsWith("Windows")) {
		// Sort if not windows
		Arrays.sort(list);
	}

	return list;
}
 
Example #4
Source File: TestCodeUtils.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
public static void compileModel(final File destinationFolder) throws IOException {

        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        final File[] javaFiles = destinationFolder.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(final File dir, final String name) {
                return name.endsWith(".java");
            }
        });

        final Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaFiles);
        compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();
        fileManager.close();
    }
 
Example #5
Source File: FileDialog.java    From ExoplayerExample with The Unlicense 6 votes vote down vote up
private void loadFileList(File path) {
    this.currentPath = path;
    List<String> r = new ArrayList<>();
    if (path.exists()) {
        if (path.getParentFile() != null) r.add(PARENT_DIR);
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String filename) {
                File sel = new File(dir, filename);
                if (!sel.canRead()) return false;
                if (selectDirectoryOption) return sel.isDirectory();
                else {
                    boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                    return endsWith || sel.isDirectory();
                }
            }
        };
        String[] fileList1 = path.list(filter);
        for (String file : fileList1) {
            r.add(file);
        }
    }
    fileList = (String[]) r.toArray(new String[]{});
}
 
Example #6
Source File: TestFileSystemOutput.java    From envelope with Apache License 2.0 6 votes vote down vote up
@Test
public void writeJsonNoOptions() throws Exception {
  Map<String, Object> paramMap = new HashMap<>();
  paramMap.put(FileSystemOutput.FORMAT_CONFIG, "json");
  paramMap.put(FileSystemOutput.PATH_CONFIG, results.getPath());
  config = ConfigFactory.parseMap(paramMap);

  FileSystemOutput fileSystemOutput = new FileSystemOutput();
  assertNoValidationFailures(fileSystemOutput, config);
  fileSystemOutput.configure(config);
  fileSystemOutput.applyBulkMutations(plannedRows);

  File[] files = results.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      return name.endsWith(".json");
    }
  });
  assertEquals("Incorrect number of JSON files", 1, files.length);

  BufferedReader br = new BufferedReader(new FileReader(files[0]));
  String line = br.readLine();
  assertEquals("Invalid first record", "{\"field1\":0,\"field2\":\"zero\",\"field3\":true,\"field4\":\"dog\"}", line);
}
 
Example #7
Source File: FileOperateUtils.java    From LLApp with Apache License 2.0 6 votes vote down vote up
/**
 * 获取目标文件夹内指定后缀名的文件数组,按照修改日期排序
 *
 * @param file      目标文件夹
 * @param extension 指定后缀名
 * @param content   包含的内容,用以查找视频缩略图
 * @return
 */
public static List<File> listFiles(File file, final String extension, final String content) {
    File[] files = null;
    if (file == null || !file.exists() || !file.isDirectory())
        return null;
    files = file.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File arg0, String arg1) {
            // TODO Auto-generated method stub
            if (content == null || content.equals(""))
                return arg1.endsWith(extension);
            else {
                return arg1.contains(content) && arg1.endsWith(extension);
            }
        }
    });
    if (files != null) {
        List<File> list = new ArrayList<File>(Arrays.asList(files));
        sortList(list, false);
        return list;
    }
    return null;
}
 
Example #8
Source File: FileUtils.java    From AcgClub with MIT License 6 votes vote down vote up
/**
 * 获取目录下所有符合filter的文件
 *
 * @param dir 目录
 * @param filter 过滤器
 * @param isRecursive 是否递归进子目录
 * @return 文件链表
 */
public static List<File> listFilesInDirWithFilter(File dir, FilenameFilter filter,
    boolean isRecursive) {
  if (isRecursive) {
    return listFilesInDirWithFilter(dir, filter);
  }
  if (dir == null || !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.getParentFile(), file.getName())) {
        list.add(file);
      }
    }
  }
  return list;
}
 
Example #9
Source File: YarnTestBase.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Locate a file or directory.
 */
public static File findFile(String startAt, FilenameFilter fnf) {
	File root = new File(startAt);
	String[] files = root.list();
	if (files == null) {
		return null;
	}
	for (String file : files) {
		File f = new File(startAt + File.separator + file);
		if (f.isDirectory()) {
			File r = findFile(f.getAbsolutePath(), fnf);
			if (r != null) {
				return r;
			}
		} else if (fnf.accept(f.getParentFile(), f.getName())) {
			return f;
		}
	}
	return null;
}
 
Example #10
Source File: FileUtils.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes all files (not directories) in the given directory (recursive)
 * that match the given filename filter. If any file cannot be deleted then
 * this is printed at warn to the given logger.
 *
 * @param directory to delete contents of
 * @param filter if null then no filter is used
 * @param logger to notify
 * @param recurse will look for contents of sub directories.
 * @param deleteEmptyDirectories default is false; if true will delete
 * directories found that are empty
 * @throws IOException if abstract pathname does not denote a directory, or
 * if an I/O error occurs
 */
public static void deleteFilesInDirectory(final File directory, final FilenameFilter filter, final Logger logger, final boolean recurse, final boolean deleteEmptyDirectories) throws IOException {
    // ensure the specified directory is actually a directory and that it exists
    if (null != directory && directory.isDirectory()) {
        final File ingestFiles[] = directory.listFiles();
        if (ingestFiles == null) {
            // null if abstract pathname does not denote a directory, or if an I/O error occurs
            throw new IOException("Unable to list directory content in: " + directory.getAbsolutePath());
        }
        for (File ingestFile : ingestFiles) {
            boolean process = (filter == null) ? true : filter.accept(directory, ingestFile.getName());
            if (ingestFile.isFile() && process) {
                FileUtils.deleteFile(ingestFile, logger, 3);
            }
            if (ingestFile.isDirectory() && recurse) {
                FileUtils.deleteFilesInDirectory(ingestFile, filter, logger, recurse, deleteEmptyDirectories);
                if (deleteEmptyDirectories && ingestFile.list().length == 0) {
                    FileUtils.deleteFile(ingestFile, logger, 3);
                }
            }
        }
    }
}
 
Example #11
Source File: BuildCmd.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: BaseTestCase.java    From Komondor with GNU General Public License v3.0 6 votes vote down vote up
protected void cleanupTempFiles(final File exampleTempFile, final String tempfilePrefix) {

        File tempfilePath = exampleTempFile.getParentFile();

        File[] possibleFiles = tempfilePath.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return (name.indexOf(tempfilePrefix) != -1 && !exampleTempFile.getName().equals(name));
            }
        });

        if (possibleFiles != null) {
            for (int i = 0; i < possibleFiles.length; i++) {
                try {
                    possibleFiles[i].delete();
                } catch (Throwable t) {
                    // ignore, we're only making a best effort cleanup attempt here
                }
            }
        }
    }
 
Example #13
Source File: NNUpgradeUtil.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Perform any steps that must succeed across all storage dirs/JournalManagers
 * involved in an upgrade before proceeding onto the actual upgrade stage. If
 * a call to any JM's or local storage dir's doPreUpgrade method fails, then
 * doUpgrade will not be called for any JM. The existing current dir is
 * renamed to previous.tmp, and then a new, empty current dir is created.
 *
 * @param conf configuration for creating {@link EditLogFileOutputStream}
 * @param sd the storage directory to perform the pre-upgrade procedure.
 * @throws IOException in the event of error
 */
static void doPreUpgrade(Configuration conf, StorageDirectory sd)
    throws IOException {
  LOG.info("Starting upgrade of storage directory " + sd.getRoot());

  // rename current to tmp
  renameCurToTmp(sd);

  final File curDir = sd.getCurrentDir();
  final File tmpDir = sd.getPreviousTmp();
  List<String> fileNameList = IOUtils.listDirectory(tmpDir, new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      return dir.equals(tmpDir)
          && name.startsWith(NNStorage.NameNodeFile.EDITS.getName());
    }
  });

  for (String s : fileNameList) {
    File prevFile = new File(tmpDir, s);
    File newFile = new File(curDir, prevFile.getName());
    Files.createLink(newFile.toPath(), prevFile.toPath());
  }
}
 
Example #14
Source File: FileUtils.java    From AcgClub with MIT License 6 votes vote down vote up
/**
 * 获取目录下所有符合filter的文件包括子目录
 *
 * @param dir 目录
 * @param filter 过滤器
 * @return 文件链表
 */
public static List<File> listFilesInDirWithFilter(File dir, FilenameFilter filter) {
  if (dir == null || !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.getParentFile(), file.getName())) {
        list.add(file);
      }
      if (file.isDirectory()) {
        list.addAll(listFilesInDirWithFilter(file, filter));
      }
    }
  }
  return list;
}
 
Example #15
Source File: JsonLexerTest.java    From pxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimple() throws IOException {
	File testsDir = new File("src/test/resources/lexer-tests");
	File[] jsonFiles = testsDir.listFiles(new FilenameFilter() {
		public boolean accept(File file, String s) {
			return s.endsWith(".json");
		}
	});

	for (File jsonFile : jsonFiles) {
		File stateFile = new File(jsonFile.getAbsolutePath() + ".state");
		if (stateFile.exists()) {
			runTest(jsonFile, stateFile);
		}
	}
}
 
Example #16
Source File: InstalledSolidityCompilerPreferencePage.java    From uml2solidity with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param list
 * @param file2
 */
private void testAndAdd(Set<SolC> list, File file2) {
	if (file2 == null)
		return;
	
	File[] listFiles2 = file2.listFiles(new FilenameFilter() {
		@Override
		public boolean accept(File dir, String name) {
			return "solc".equals(name);
		}
	});
	if (listFiles2 != null && listFiles2.length == 1) {
		SolC testSolCFile = testSolCFile(listFiles2[0]);
		if (testSolCFile != null)
			list.add(testSolCFile);
	}
}
 
Example #17
Source File: FileUtils.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
private static List<File> searchFiles(File dir, FilenameFilter filter) {
    List<File> result = new ArrayList<File>();
    File[] filesFiltered = dir.listFiles(filter), filesAll = dir.listFiles();

    if (filesFiltered != null) {
        result.addAll(Arrays.asList(filesFiltered));
    }

    if (filesAll != null) {
        for (File file : filesAll) {
            if (file.isDirectory()) {
                List<File> deeperList = searchFiles(file, filter);
                result.addAll(deeperList);
            }
        }
    }
    return result;
}
 
Example #18
Source File: RubyScript.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
private void loadAssertionProvidersFromDir(final File dirFile) {
    File[] listFiles = dirFile.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return dir.equals(dirFile) && name.endsWith(".rb");
        }
    });
    if (listFiles != null) {
        for (File listFile : listFiles) {
            try {
                String fileName = listFile.getName();
                interpreter.executeScript("require '" + fileName.substring(0, fileName.length() - 3) + "'", "<internal>");
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
    findAssertionProviderMethods();
}
 
Example #19
Source File: FsDatasetUtil.java    From big-c with Apache License 2.0 6 votes vote down vote up
/** Find the corresponding meta data file from a given block file */
public static File findMetaFile(final File blockFile) throws IOException {
  final String prefix = blockFile.getName() + "_";
  final File parent = blockFile.getParentFile();
  final File[] matches = parent.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      return dir.equals(parent) && name.startsWith(prefix)
          && name.endsWith(Block.METADATA_EXTENSION);
    }
  });

  if (matches == null || matches.length == 0) {
    throw new IOException("Meta file not found, blockFile=" + blockFile);
  }
  if (matches.length > 1) {
    throw new IOException("Found more than one meta files: " 
        + Arrays.asList(matches));
  }
  return matches[0];
}
 
Example #20
Source File: TestAnonymousClass.java    From Box with Apache License 2.0 5 votes vote down vote up
public int test() {
	String[] files = new File("a").list(new FilenameFilter() {
		@Override
		public boolean accept(File dir, String name) {
			return name.equals("a");
		}
	});
	return files.length;
}
 
Example #21
Source File: Animation.java    From GIFKR with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static FilenameFilter getPNGSFilter() {
	return new FilenameFilter() {
		@Override
		public boolean accept(File dir, String name) {
			return name.matches("[0-9]*\\.png");
		}	
	};
}
 
Example #22
Source File: FileUtil.java    From qaf with MIT License 5 votes vote down vote up
public static FilenameFilter getFileFilterFor(final StringComparator c, final String... qnames) {
	FilenameFilter filter = new FilenameFilter() {
		public boolean accept(File dir, String name) {
			for (String qname : qnames) {
				if (StringUtil.isNotBlank(qname) && c.compareIgnoreCase(name, qname))
					return true;
			}
			return false;
		}
	};

	return filter;
}
 
Example #23
Source File: HdfsSinkConfigurationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@After
public void checkFilesClosedOK() throws IOException {
	applicationContext.close();
	File testOutput = new File(testDir);
	assertTrue(testOutput.exists());
	File[] files = testOutput.listFiles(new FilenameFilter() {

		@Override
		public boolean accept(File dir, String name) {
			return name.endsWith(".txt");
		}

	});
	assertTrue(files.length > 1);
}
 
Example #24
Source File: ThriftLogGenerator.java    From singer with Apache License 2.0 5 votes vote down vote up
private void removeLogFileIfNeeded(int numOfLogFiles) throws IOException {
  File dir = new File(logDir);
  FilenameFilter filter = new PrefixFileFilter(logFileName);
  List<File> files = Arrays.asList(dir.listFiles(filter));
  Collections.sort(files, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
  if (files.size() > numOfLogFiles) {
    for (int i = 0; i < files.size() - numOfLogFiles; ++i) {
      FileUtils.forceDelete(files.get(i));
      System.out.print(
          String.format(
              "Removed log file: %s.\n",
              files.get(i).getPath()));
    }
  }
}
 
Example #25
Source File: FileUtil.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public static String[] getFileList(String path, FilenameFilter filter) {
    File mPath = new File(path);
    try {
        mPath.mkdirs();
        if (mPath.exists()) {
            return mPath.list(filter);
        }
    } catch (SecurityException e) {
    }
    return new String[0];
}
 
Example #26
Source File: FileUtil.java    From FimiX8-RE with MIT License 5 votes vote down vote up
public static List<File> listFiles(File file, final String extension, final String content) {
    if (file == null || !file.exists() || !file.isDirectory()) {
        return null;
    }
    File[] files = file.listFiles(new FilenameFilter() {
        public boolean accept(File arg0, String arg1) {
            if (content == null || content.equals("")) {
                return arg1.endsWith(extension);
            }
            return arg1.contains(content) && arg1.endsWith(extension);
        }
    });
    if (files == null) {
        return null;
    }
    List<File> list = new ArrayList(Arrays.asList(files));
    sortList(list, false);
    return list;
}
 
Example #27
Source File: FileHandlingTools.java    From tsml with GNU General Public License v3.0 5 votes vote down vote up
/**
 * List the directories contained in the directory given
 */
public static String[] listDirectoryNames(String baseDirectory) {
    return (new File(baseDirectory)).list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return dir.isDirectory();
        }
    });
}
 
Example #28
Source File: JFrameConf.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
public HashSet addInJListFromDirectory(URI filePathURI){
    //creation d'un filtre pour ne recuperer que les fichiers *.properties
    FilenameFilter propertiesFilter = new FilenameFilter() {
        public boolean accept(File arg0, String arg1) {
            return arg1.endsWith(".properties");
        }
    };
    File filePath = new File (filePathURI);
    HashSet<String> set = new HashSet<String>();
    for (int i = 0; i < filePath.list(propertiesFilter).length; i++){
        set.add(filePath.list(propertiesFilter)[i]);
    }        
    return set;
}
 
Example #29
Source File: OnlineDbMVStore.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public List<OnlineWorkflowDetails> listWorkflows(Interval basecaseInterval) {
    LOGGER.info("Getting list of stored workflows run on basecases within the interval {}", basecaseInterval);
    String dateFormatPattern = "yyyyMMdd_HHmm";
    DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormatPattern);
    List<OnlineWorkflowDetails> workflowIds = new ArrayList<OnlineWorkflowDetails>();
    File[] files = config.getOnlineDbDir().toFile().listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().startsWith(STORED_WORKFLOW_PREFIX);
        }
    });
    for (File file : files) {
        if (file.isFile()) {
            String workflowId = file.getName().substring(STORED_WORKFLOW_PREFIX.length());
            if (workflowId.length() > dateFormatPattern.length() && workflowId.substring(dateFormatPattern.length(), dateFormatPattern.length() + 1).equals("_")) {
                String basecaseName = workflowId.substring(0, dateFormatPattern.length() - 1);
                DateTime basecaseDate = DateTime.parse(basecaseName, formatter);
                if (basecaseInterval.contains(basecaseDate.getMillis())) {
                    OnlineWorkflowDetails workflowDetails = new OnlineWorkflowDetails(workflowId);
                    workflowDetails.setWorkflowDate(getWorkflowDate(workflowId));
                    workflowIds.add(workflowDetails);
                }
            }
        }
    }
    Collections.sort(workflowIds, new Comparator<OnlineWorkflowDetails>() {
        @Override
        public int compare(OnlineWorkflowDetails wfDetails1, OnlineWorkflowDetails wfDetails2) {
            return wfDetails1.getWorkflowDate().compareTo(wfDetails2.getWorkflowDate());
        }
    });
    LOGGER.info("Found {} workflow(s)", workflowIds.size());
    return workflowIds;
}
 
Example #30
Source File: CrashlyticsReportPersistence.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
@NonNull
private static List<File> getFilesInDirectory(
    @NonNull File directory, @Nullable FilenameFilter filter) {
  if (!directory.isDirectory()) {
    return Collections.emptyList();
  }
  final File[] files = (filter == null) ? directory.listFiles() : directory.listFiles(filter);
  return (files != null) ? Arrays.asList(files) : Collections.emptyList();
}