Java Code Examples for java.io.FilenameFilter

The following are top voted examples for showing how to use java.io.FilenameFilter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: convertigo-engine   File: TracePlayerManager.java   Source Code and License 6 votes vote down vote up
public Collection<String> getEtr(){
	Collection<File> res = new LinkedList<File>();
	File[] listdir = new File(Engine.PROJECTS_PATH).listFiles();
	for(File s : listdir){
		File tracedir = new File(s,"Traces");
		if(tracedir.exists()&&tracedir.isDirectory()){
			File[] listconnectors = tracedir.listFiles();
			for(File s2 : listconnectors){
				res.addAll(Arrays.asList(s2.listFiles(new FilenameFilter(){
					public boolean accept(File arg0, String arg1) {
						return arg1.endsWith(".etr");
					}
				})));
			}
		}
	}
	Collection<String> listetr = new ArrayList<String>(res.size());
	for(File f : res)
		listetr.add(f.getPath().substring(Engine.PROJECTS_PATH.length()));
	return listetr;
}
 
Example 2
Project: DecompiledMinecraft   File: AnvilSaveConverter.java   Source Code and License 6 votes vote down vote up
/**
 * filters the files in the par1 directory, and adds them to the par2 collections
 */
private void addRegionFilesToCollection(File worldDir, Collection<File> collection)
{
    File file1 = new File(worldDir, "region");
    File[] afile = file1.listFiles(new FilenameFilter()
    {
        public boolean accept(File p_accept_1_, String p_accept_2_)
        {
            return p_accept_2_.endsWith(".mcr");
        }
    });

    if (afile != null)
    {
        Collections.addAll(collection, afile);
    }
}
 
Example 3
Project: take   File: ProxyParseFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test01() throws Exception {
    String basePackage = "/com.jt.core.proxy";
    basePackage = basePackage.replaceAll(".", "/");
    Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(basePackage);
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        String file = url.getFile();
        File f = new File(file);
        if (f.exists()) {
            File[] classes = f.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith("class");
                }
            });
            for (File c : classes) {
                System.out.println(c);
            }
        }
    }

}
 
Example 4
Project: flume-release-1.7.0   File: TestFileChannelIntegrityTool.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  checkpointDir = new File(baseDir, "checkpoint");
  dataDir = new File(baseDir, "dataDir");
  Assert.assertTrue(checkpointDir.mkdirs() || checkpointDir.isDirectory());
  Assert.assertTrue(dataDir.mkdirs() || dataDir.isDirectory());
  File[] dataFiles = origDataDir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      if (name.contains("lock")) {
        return false;
      }
      return true;
    }
  });
  for (File dataFile : dataFiles) {
    Serialization.copyFile(dataFile, new File(dataDir, dataFile.getName()));
  }
}
 
Example 5
Project: BBLIB   File: Logger.java   Source Code and License 6 votes vote down vote up
public static Collection<File> getAllLogFiles()
{
	FilenameFilter logFilter = new FilenameFilter()
	{
		public boolean accept(File dir, String name)
		{
			String lowercaseName = name.toLowerCase();
			return lowercaseName.matches("\\d\\d\\d\\d.log");
		}
	};
	File logDir = getLogDirectory();
	File[] files = logDir.listFiles(logFilter);
	if (files == null)
	{
		return new ArrayList<File>();
	}
	else
	{
		return (Collection<File>) Arrays.asList(files);
	}
}
 
Example 6
Project: Transwarp-Sample-Code   File: LocalFileSource.java   Source Code and License 6 votes vote down vote up
private List<File> findFile(File path, boolean isRecurse) {
    // 递归查找文件
    List<File> files = new ArrayList<File>();
    if (path.isDirectory()) {
        File[] candidates = path.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                if(name.endsWith(".swp")||name.endsWith(fileSuffix)||ignorePattern.matcher(name).matches()){
                    return false;
                }
                return true;
            }
        });
        for (int i = 0; i < candidates.length; i++) {
            if (candidates[i].isDirectory() && isRecurse) {
                files.addAll(findFile(candidates[i], isRecurse));
            } else {
                files.add(candidates[i]);
            }
        }
    }
    return files;
}
 
Example 7
Project: monarch   File: WriteAheadLog.java   Source Code and License 6 votes vote down vote up
/**
 * Get a list of files which are under process
 * 
 * @return list of file which are currently being used by WAL writers
 */

public String[] getInprogressFiles() {
  if (!initialized) {
    return null;
  }
  String[] files = walDirectory.toFile().list(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      if (name.endsWith(WAL_INPROGRESS_SUFFIX))
        return true;
      return false;
    }
  });
  if (null != files && files.length > 0) {
    Arrays.sort(files, new WALFileComparator());
  }
  return files;
}
 
Example 8
Project: incubator-netbeans   File: HistoryTest.java   Source Code and License 6 votes vote down vote up
private List<File> prepareVersions (File file) throws Exception {
    List<File> revisionList = new LinkedList<File>();
    File dataDir = new File(getDataDir(), "versionscache");
    File[] revisions = dataDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith("rev");
        }
    });
    for (File rev : revisions) {
        if (rev.isFile()) {
            revisionList.add(0, rev);
            Utils.copyStreamsCloseAll(new FileOutputStream(file), new FileInputStream(rev));
            commit(new File[] {file});
        }
    }
    return revisionList;
}
 
Example 9
Project: tqdev-metrics   File: InfluxDbFileReporter.java   Source Code and License 6 votes vote down vote up
/**
 * Compress.
 *
 * @param filename
 *            the filename
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private void compress(String filename) throws IOException {
	File current = new File(filename);
	File dir = new File(metricPath);
	FilenameFilter textFileFilter = (f, s) -> s.endsWith(".txt");
	File[] directoryListing = dir.listFiles(textFileFilter);
	if (directoryListing != null) {
		for (File file : directoryListing) {
			if (file.getCanonicalPath() != current.getCanonicalPath()) {
				try (FileOutputStream fos = new FileOutputStream(file.getPath() + ".gz");
						GZIPOutputStream gzos = new GZIPOutputStream(fos)) {
					byte[] buffer = new byte[8192];
					int length;
					try (FileInputStream fis = new FileInputStream(file.getPath())) {
						while ((length = fis.read(buffer)) > 0) {
							gzos.write(buffer, 0, length);
						}
					}
				}
				file.delete();
			}
		}
	} else {
		throw new IOException("Directory not listable: " + metricPath);
	}
}
 
Example 10
Project: Pogamut3   File: ServerRunner.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes a list of {@link IEvaluationTask} represented in XML by
 * XSTream serialization. Uses passed directory or current of omitted.
 *
 * @param args
 */
public void initTasks(String[] args) {
    tasks = new ArrayList<File>();

    String evalDir = ".";
    if (args.length >= 1) {
        evalDir = args[0];
    }
    File x = new File(evalDir);
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".eval.xml");
        }
    };
    tasks.addAll(Arrays.asList(x.listFiles(filter)));
    if (args.length >= 2) {
        isResume = args[1].equals("--resume");
        if(!isResume) {
            label = args[1];
        } else if(args.length >= 3) {
            label = args[2];
        }
    }
}
 
Example 11
Project: LJFramework   File: FileUtils.java   Source Code and 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 12
Project: apache-tomcat-7.0.73-with-comment   File: IntrospectionUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Return all files with a given extension in a dir
 * @deprecated Is used only by deprecated method
 */
@Deprecated
public static String[] getFilesByExt(String ld, String ext) {
    File dir = new File(ld);
    String[] names = null;
    final String lext = ext;
    if (dir.isDirectory()) {
        names = dir.list(new FilenameFilter() {
            @Override
            public boolean accept(File d, String name) {
                if (name.endsWith(lext)) {
                    return true;
                }
                return false;
            }
        });
    }
    return names;
}
 
Example 13
Project: FireFiles   File: FileUtils.java   Source Code and License 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 14
Project: marathonv5   File: JavaProfile.java   Source Code and License 6 votes vote down vote up
private static String findFile(String[] likelyPlaces, final String namePattern) {
    String path = null;
    for (String likelyPlace : likelyPlaces) {
        File[] f = new File(likelyPlace).listFiles(new FilenameFilter() {
            @Override public boolean accept(File dir, String name) {
                return name.matches(namePattern);
            }
        });
        if (f != null && f.length == 1) {
            try {
                path = f[0].getCanonicalPath();
                break;
            } catch (IOException e) {
            }
        }
    }
    ;
    return path;
}
 
Example 15
Project: Coder   File: FileUtils.java   Source Code and 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 16
Project: OpenVertretung   File: BaseTestCase.java   Source Code and License 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
Project: Hydrograph   File: XMLConfigUtil.java   Source Code and License 6 votes vote down vote up
/** Creates a file name filter in order to filter out only the required files.
 * @param extention the files to be filtered on ex. .xml
 * @return FilenameFilter 
 */
public FilenameFilter getFileNameFilter(final String extention) {
	FilenameFilter filenameFilter = new FilenameFilter() {
		
		@Override
		public boolean accept(File dir, String name) {
		  if(name.lastIndexOf('.')>0)
              {
                 // get last index for '.' char
                 int lastIndex = name.lastIndexOf('.');
                 
                 // get extension
                 String str = name.substring(lastIndex);
                 
                 // match path name extension
                 if(str.equals(extention))
                 {
                    return true;
                 }
              }
              return false;
		}
	};
	return filenameFilter;
}
 
Example 18
Project: EasyAndroid   File: FileTool.java   Source Code and License 6 votes vote down vote up
/**
 * 返回file目录下所有不包含names列表中任意名称的文件列表,不区分大小写
 *
 * @param file  文件
 * @param names 名称列表
 * @return 文件列表
 */
public static File[] listFilesDislikeNamesNoCase(File file, String... names)
{
    final List<String> list = getNamesList(names, true);
    return file.listFiles(new FilenameFilter()
    {
        @Override
        public boolean accept(File dir, String name)
        {
            String lowerName = name.toLowerCase();
            for(String s : list)
            {
                if(lowerName.contains(s))
                {
                    return false;
                }
            }

            return true;
        }
    });
}
 
Example 19
Project: EasyAndroid   File: FileTool.java   Source Code and License 6 votes vote down vote up
/**
 * 返回file目录下所有包含names列表中任意名称的文件列表
 *
 * @param file  文件
 * @param names 名称列表
 * @return 文件列表
 */
public static File[] listFilesLikeNames(File file, final String... names)
{
    final List<String> list = getNamesList(names);
    return file.listFiles(new FilenameFilter()
    {
        @Override
        public boolean accept(File dir, String name)
        {
            for(String s : list)
            {
                if(name.contains(s))
                {
                    return true;
                }
            }

            return false;
        }
    });
}
 
Example 20
Project: Android-FileBrowser-FilePicker   File: FileNavigator.java   Source Code and 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) {
               String fileExtension = FilenameUtils.getExtension(name);
               if(mAllowedFileExtensionFilter.contains(fileExtension) || fileExtension.isEmpty() )
                   return true;
               else
                   return false;
           }
       };
       return mCurrentNode.listFiles(fileNameFilter);
   }
   return mCurrentNode.listFiles();
}
 
Example 21
Project: monarch   File: WriteAheadLog.java   Source Code and License 6 votes vote down vote up
/**
 * Get a list of files which are done
 * 
 * @return list of file which are done by WAL writers
 */

public String[] getDoneFiles() {
  if (!initialized) {
    return null;
  }
  String[] files = walDirectory.toFile().list(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
      if (name.endsWith(WAL_DONE_SUFFIX))
        return true;
      return false;
    }
  });
  if (null != files && files.length > 0) {
    Arrays.sort(files, new WALFileComparator());
  }
  return files;
}
 
Example 22
Project: sealtalk-android-master   File: RongDatabaseFilesProvider.java   Source Code and License 6 votes vote down vote up
private List<File> listFiles(File dir, FilenameFilter fileNameFilter) {
    if (dir == null || dir.isFile()) {
        return null;
    }
    List<File> fileList = new ArrayList<>();
    File[] files = dir.listFiles();
    if (files != null) {
        for (File file : files) {
            if (file.isFile() && fileNameFilter.accept(dir, file.getName())) {
                fileList.add(file);
            } else {
                List<File> tmp = listFiles(file, fileNameFilter);
                if (tmp != null && tmp.size() > 0) {
                    fileList.addAll(tmp);
                }
            }
        }
    }
    return fileList;
}
 
Example 23
Project: devenv   File: CoreToolProvider.java   Source Code and License 6 votes vote down vote up
@Nullable
private String findInstalledVersion(String installDir)
{
    File libDir = new File(installDir + "/lib");
    if (libDir.exists() && libDir.isDirectory() && libDir.canRead())
    {
        FilenameFilter coreFilter = (dir, name) -> name.startsWith(id() + "-core-");
        File[] cores = libDir.listFiles(coreFilter);
        if (cores != null)
        {
            String coreVersion = null;
            for (File core : cores)
            {
                String ver = extractVersionFromCoreName(core.getName());
                if (ver != null &&
                    (coreVersion == null || coreVersion.compareTo(ver) < 0))
                {
                    coreVersion = ver;
                }
            }
            return coreVersion;
        }
    }
    return null;
}
 
Example 24
Project: Backmemed   File: AnvilSaveConverter.java   Source Code and License 6 votes vote down vote up
/**
 * filters the files in the par1 directory, and adds them to the par2 collections
 */
private void addRegionFilesToCollection(File worldDir, Collection<File> collection)
{
    File file1 = new File(worldDir, "region");
    File[] afile = file1.listFiles(new FilenameFilter()
    {
        public boolean accept(File p_accept_1_, String p_accept_2_)
        {
            return p_accept_2_.endsWith(".mcr");
        }
    });

    if (afile != null)
    {
        Collections.addAll(collection, afile);
    }
}
 
Example 25
Project: easyfilemanager   File: FileUtils.java   Source Code and License 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 26
Project: Intelligent_Indoor_Localization_System   File: SelectFileDialog.java   Source Code and License 6 votes vote down vote up
private void loadFileList(File path) {
    this.currentPath = path;
    List<String> r = new ArrayList<String>();
    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 27
Project: ProyectoPacientes   File: BaseTestCase.java   Source Code and License 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 28
Project: the-vigilantes   File: BaseTestCase.java   Source Code and License 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 29
Project: gen_code   File: ConfigParser.java   Source Code and License 6 votes vote down vote up
/**
 * 获取模板路径下的所有模板文件
 * @return 所有模板文件
 */
public static Map<String,Template> getTemplates(){
    File tempFolder = new File(CoreConfig.getTemplatePath());
    File[] files = null;
    if(tempFolder.exists()&&tempFolder.isDirectory()){
        files = tempFolder.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return true;
                //name.endsWith(".ftl");
            }
        });
    }
    Map<String,Template> templateConfig =  new HashMap<String, Template>();
    for(File f : files){
        templateConfig.put(f.getName(),new Template(f.getName(),CoreConfig.getGenPath()));
    }
    return templateConfig;
}
 
Example 30
Project: Panako   File: TestUtilities.java   Source Code and License 6 votes vote down vote up
public static File[] getResources(String folderName, final String ext){
	String file = "/be/panako/tests/res/" + folderName;
	final URL url = TestUtilities.class.getResource(file);
	try {
		 File folder = new File(new URI(url.toString()));
		 return folder.listFiles(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(ext.toLowerCase());
			}
		});
	} catch (URISyntaxException e) {
		return null;
	}
}
 
Example 31
Project: Panako   File: TestUtilities.java   Source Code and License 6 votes vote down vote up
public static File[] getRandomRefQueryPair(){
	FilenameFilter mp3Filter = new FilenameFilter() {
		
		@Override
		public boolean accept(File dir, String name) {
			return name.endsWith(".mp3");
		}
	};
	File[] referenceFiles = new File(refFolder).listFiles(mp3Filter);
	File[] queryFiles = new File(queryFolder).listFiles(mp3Filter);
	
	File referenceFile = referenceFiles[new Random().nextInt(referenceFiles.length)];
	File queryFile = null;
	String refName = referenceFile.getName();
	for(File q : queryFiles ){
		if(q.getName().startsWith(refName.substring(0, 5))){
			queryFile = q;
		}
	}
	File[] pair = {referenceFile,queryFile};
	return pair;
}
 
Example 32
Project: gitplex-mit   File: DefaultPersistManager.java   Source Code and License 5 votes vote down vote up
@Sessional
@Override
public void importData(Metadata metadata, File dataDir) {
	Session session = dao.getSession();
	List<Class<?>> entityTypes = getEntityTypes(sessionFactory);
	Collections.reverse(entityTypes);
	for (Class<?> entityType: entityTypes) {
		File[] dataFiles = dataDir.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.startsWith(entityType.getSimpleName() + "s.xml");
			}
			
		});
		for (File file: dataFiles) {
			try {
				logger.info("Importing from data file '" + file.getName() + "'...");
				session.beginTransaction();
				VersionedDocument dom = VersionedDocument.fromFile(file);
				
				for (Element element: dom.getRootElement().elements()) {
					element.detach();
					AbstractEntity entity = (AbstractEntity) new VersionedDocument(DocumentHelper.createDocument(element)).toBean();
					session.replicate(entity, ReplicationMode.EXCEPTION);
				}
				session.flush();
				session.clear();
				session.getTransaction().commit();
			} catch (Throwable e) {
				session.getTransaction().rollback();
				throw Throwables.propagate(e);
			}
		}
	}	
}
 
Example 33
Project: diary   File: Diary.java   Source Code and License 5 votes vote down vote up
private static File[] listDays(File monthDir)
{
    return sortFiles(monthDir.listFiles(new FilenameFilter()
    {
        // accept
        @Override
        public boolean accept(File dir, String filename)
        {
            return filename.matches("^[0-9]{2}.txt$");
        }
    }));
}
 
Example 34
Project: jaffa-framework   File: FindFiles.java   Source Code and License 5 votes vote down vote up
private void findFiles() {

        // Create the filter to use when searching for files
        // This could be enhanced to use a wildcard filter object if needed!!!!
        FilenameFilter filter = new DirFilter();

        // Tokenize the list of directories and loop through each one.
        StringTokenizer st = new StringTokenizer(m_pathList,File.pathSeparator);
        while (st.hasMoreTokens()) {
            String path = st.nextToken();
            File f = new File(path);
            // Only process this entry if it's a directory
            if(f.isDirectory()) {

                // Get all sub-directories under this root.
                DirList structure = new DirList(path);

                // For each sub directory, search it for any of the required file names
                for(Iterator it = structure.getList().iterator(); it.hasNext();) {
                    File dir = (File) it.next();
                    File[] list = dir.listFiles( filter );

                    // For any matching files, add it to the search results (assming it not in there already!)
                    for(int i = 0; i<list.length; i++)
                        if(!m_filesFound.contains(list[i]))
                            m_filesFound.add(list[i]);
                }
            }
        }
    }
 
Example 35
Project: BaseCore   File: FileUtils.java   Source Code and License 5 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 36
Project: codedemos   File: FileUtil.java   Source Code and License 5 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 37
Project: spark-project   File: ClassSearcher.java   Source Code and License 5 votes vote down vote up
/**
 * 查找jar包中的class
 * 
 * @param baseDirName
 *            jar路径
 * @param includeJars
 */
private List<String> findjarFiles(String baseDirName, final List<String> includeJars) {
    List<String> classFiles = Lists.newArrayList();
    try {
        // 判断目录是否存在
        File baseDir = new File(baseDirName);
        if (!baseDir.exists() || !baseDir.isDirectory()) {
            LOG.error("file serach error:" + baseDirName + " is not a dir!");
        } else {
            String[] filelist = baseDir.list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return includeAllJarsInLib || includeJars.contains(name);
                }
            });
            for (int i = 0; i < filelist.length; i++) {
                JarFile localJarFile = new JarFile(new File(baseDirName + File.separator + filelist[i]));
                Enumeration<JarEntry> entries = localJarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry jarEntry = entries.nextElement();
                    String entryName = jarEntry.getName();
                    if (!jarEntry.isDirectory() && entryName.endsWith(".class")) {
                        String className = entryName.replaceAll("/", ".").substring(0, entryName.length() - 6);
                        classFiles.add(className);
                    }
                }
                localJarFile.close();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return classFiles;

}
 
Example 38
Project: SkinFramework   File: SkinHelper.java   Source Code and License 5 votes vote down vote up
String[] getSkinArchive() {
    return new File(SKIN_ROOT).list(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String filename) {
            return filename.endsWith(".skin");
        }
    });
}
 
Example 39
Project: incubator-netbeans   File: CheckBundles.java   Source Code and License 5 votes vote down vote up
private void scanSubdirs(File file, Collection<File> bundles, Map<File,String[]> srcs) throws Exception {
    log("scanSubdirs "+file, Project.MSG_DEBUG);
    File [] subdirs = file.listFiles(new FilenameFilter () {
            public boolean accept (File f, String name) {
                return new File(f, name).isDirectory();
            }
        });
    for (int i = 0; i<subdirs.length; i++) {
        scan (subdirs[i], bundles, srcs);
        scanSubdirs (subdirs[i], bundles, srcs);
    }

}
 
Example 40
Project: incubator-netbeans   File: MavenSettings.java   Source Code and License 5 votes vote down vote up
public static @CheckForNull String getCommandLineMavenVersion(File mavenHome) {
    File[] jars = new File(mavenHome, "lib").listFiles(new FilenameFilter() { // NOI18N
        public @Override boolean accept(File dir, String name) {
            return name.endsWith(".jar"); // NOI18N
        }
    });
    if (jars == null) {
        return null;
    }
    for (File jar : jars) {
        try {
            // Prefer to use this rather than raw ZipFile since URLMapper since ArchiveURLMapper will cache JARs:
            FileObject entry = URLMapper.findFileObject(new URL(FileUtil.urlForArchiveOrDir(jar), "META-INF/maven/org.apache.maven/maven-core/pom.properties")); // NOI18N
            if (entry != null) {
                InputStream is = entry.getInputStream();
                try {
                    Properties properties = new Properties();
                    properties.load(is);
                    return properties.getProperty("version"); // NOI18N
                } finally {
                    is.close();
                }
            }
        } catch (IOException x) {
            // ignore for now
        }
    }
    return null;
}