Java Code Examples for java.io.FilenameFilter

The following examples show how to use java.io.FilenameFilter. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: rocketmq   Source File: LoggingBuilderTest.java    License: 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 2
Source Project: FimiX8-RE   Source File: FileUtil.java    License: MIT License 6 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 3
Source Project: pxf   Source File: PartitionedJsonParserNoSeekTest.java    License: Apache License 2.0 6 votes vote down vote up
public void runTest(final File jsonFile) throws IOException {
	InputStream jsonInputStream = new FileInputStream(jsonFile);

	try {
		PartitionedJsonParser parser = new PartitionedJsonParser(jsonInputStream);

		File[] jsonObjectFiles = jsonFile.getParentFile().listFiles(new FilenameFilter() {
			public boolean accept(File file, String s) {
				return s.contains(jsonFile.getName()) && s.contains("expected");
			}
		});
		Arrays.sort(jsonObjectFiles);
		for (File jsonObjectFile : jsonObjectFiles) {
			String expected = trimWhitespaces(FileUtils.readFileToString(jsonObjectFile));
			String result = parser.nextObjectContainingMember("name");
			assertNotNull(jsonFile.getName() + "/" + jsonObjectFile.getName(), result);
			assertEquals(jsonFile.getName() + "/" + jsonObjectFile.getName(), expected, trimWhitespaces(result));
			LOG.info("File " + jsonFile.getName() + "/" + jsonObjectFile.getName() + " passed");
		}

	} finally {
		IOUtils.closeQuietly(jsonInputStream);
	}
}
 
Example 4
Source Project: big-c   Source File: NNUpgradeUtil.java    License: 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 5
@Test
public void testFromJSONAgainsCorrectManifests() throws Exception {
	URL entry = ServerTestsActivator.getContext().getBundle().getEntry(CORRECT_MANIFEST_LOCATION);
	File manifestSource = new File(FileLocator.toFileURL(entry).getPath());

	File[] manifests = manifestSource.listFiles(new FilenameFilter() {

		public boolean accept(File dir, String name) {
			return name.toLowerCase().endsWith(".yml"); //$NON-NLS-1$
		}
	});

	for (File manifestFile : manifests) {
		InputStream inputStream = new FileInputStream(manifestFile);

		/* export the manifest to JSON - pass if no exceptions occurred */
		JSONObject manifestJSON = exportManifestJSON(inputStream);
		ManifestUtils.parse(manifestJSON).toString();
	}
}
 
Example 6
Source Project: Android-FileBrowser-FilePicker   Source File: FileNavigator.java    License: MIT License 6 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 7
/**
 * 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 8
Source Project: jpa-unit   Source File: TestCodeUtils.java    License: 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 9
Source Project: ExoplayerExample   Source File: FileDialog.java    License: 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 10
Source Project: envelope   Source File: TestFileSystemOutput.java    License: 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 11
Source Project: LLApp   Source File: FileOperateUtils.java    License: 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 12
Source Project: AcgClub   Source File: FileUtils.java    License: 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 13
Source Project: flink   Source File: YarnTestBase.java    License: 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 14
Source Project: nifi-minifi   Source File: FileUtils.java    License: 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 15
Source Project: product-microgateway   Source File: BuildCmd.java    License: 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 16
Source Project: Komondor   Source File: BaseTestCase.java    License: 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 17
Source Project: hadoop   Source File: NNUpgradeUtil.java    License: 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 18
Source Project: AcgClub   Source File: FileUtils.java    License: 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 19
Source Project: pxf   Source File: JsonLexerTest.java    License: 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 20
/**
 * @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 21
Source Project: FireFiles   Source File: FileUtils.java    License: 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 22
Source Project: marathonv5   Source File: RubyScript.java    License: 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 23
Source Project: big-c   Source File: FsDatasetUtil.java    License: 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 24
Source Project: Box   Source File: TestAnonymousClass.java    License: 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 25
Source Project: GIFKR   Source File: Animation.java    License: 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 26
Source Project: qaf   Source File: FileUtil.java    License: 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 27
@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 28
Source Project: singer   Source File: ThriftLogGenerator.java    License: 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 29
Source Project: FimiX8-RE   Source File: FileUtil.java    License: 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 30
Source Project: tsml   Source File: FileHandlingTools.java    License: 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();
        }
    });
}