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: 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 #3
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 #4
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 #5
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 #6
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 #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: 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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #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: PictureDirPresenter.java    From FileManager with Apache License 2.0 5 votes vote down vote up
@Override
public void getData() {

    mView.showDialog();

    mView.setDataUsingObservable(Observable.create(new Observable.OnSubscribe<List<String>>() {
        @Override
        public void call(Subscriber<? super List<String>> subscriber) {

            mList = Arrays.asList(mDirFile.list(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String filename) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                            || filename.endsWith(".jpeg") || filename.endsWith(".gif")) {
                        return true;
                    }
                    return false;
                }
            }));

            //对获取到对路径进行拼接
            for (int i = 0; i < mList.size(); i++) {
                mList.set(i, mPath + File.separator + mList.get(i));
            }

            mView.setTotalCount(mList.size());
            mView.dimissDialog();

            Collections.reverse(mList);
            subscriber.onNext(mList);
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()));

}
 
Example #21
Source File: ListNull.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    File d = new File(".");
    go("list()", d.list());
    go("listFiles()", d.listFiles());
    go("list(null)", d.list(null));
    go("listFiles((FilenameFilter)null)", d.listFiles((FilenameFilter)null));
    go("listFiles((FileFilter)null)", d.listFiles((FileFilter)null));
}
 
Example #22
Source File: CrashHandler.java    From zone-sdk with MIT License 5 votes vote down vote up
/**
 * 获取错误报告文件名
 * 
 * @param ctx
 * @return
 */
private String[] getCrashReportFiles(Context ctx) {
	File filesDir = ctx.getFilesDir();
	FilenameFilter filter = new FilenameFilter() {
		public boolean accept(File dir, String name) {
			return name.endsWith(CRASH_REPORTER_EXTENSION);
		}
	};
	return filesDir.list(filter);
}
 
Example #23
Source File: InitializerMessageSource.java    From openmrs-module-initializer with MIT License 5 votes vote down vote up
/**
 * Scans a directory for possible message properties files and adds it to the internal map.
 * 
 * @param dirPath The directory to scan.
 */
public void addMessageProperties(String dirPath) {
	
	final File[] propFiles = new File(dirPath).listFiles(new FilenameFilter() {
		
		@Override
		public boolean accept(File dir, String name) {
			String ext = FilenameUtils.getExtension(name);
			if (StringUtils.isEmpty(ext)) { // to be safe, ext can only be null if name is null
				return false;
			}
			if (ext.equals("properties")) {
				return true; // filtering only "*.properties" files
			}
			return false;
		}
	});
	
	if (propFiles != null) {
		if (MapUtils.isEmpty(messagePropertiesMap)) {
			messagePropertiesMap = new LinkedHashMap<File, Locale>();
		}
		for (File file : propFiles) {
			// Now reading the locale info out of the base name
			String baseName = FilenameUtils.getBaseName(file.getName()); // "messages_en_GB"
			try {
				Locale locale = getLocaleFromFileBaseName(baseName); // "en_GB"
				messagePropertiesMap.put(file, locale);
			}
			catch (IllegalArgumentException e) {
				log.error(e);
			}
		}
	}
}
 
Example #24
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Try our best to migrate all files from source to target that match
 * requested prefix.
 *
 * @return the number of files moved, or -1 if there was trouble.
 */
private static int moveFiles(File sourceDir, File targetDir, final String prefix) {
    final File[] sourceFiles = FileUtils.listFilesOrEmpty(sourceDir, new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith(prefix);
        }
    });

    int res = 0;
    for (File sourceFile : sourceFiles) {
        final File targetFile = new File(targetDir, sourceFile.getName());
        Log.d(TAG, "Migrating " + sourceFile + " to " + targetFile);
        try {
            FileUtils.copyFileOrThrow(sourceFile, targetFile);
            FileUtils.copyPermissions(sourceFile, targetFile);
            if (!sourceFile.delete()) {
                throw new IOException("Failed to clean up " + sourceFile);
            }
            if (res != -1) {
                res++;
            }
        } catch (IOException e) {
            Log.w(TAG, "Failed to migrate " + sourceFile + ": " + e);
            res = -1;
        }
    }
    return res;
}
 
Example #25
Source File: SecuritySupport.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static String[] getFileList(final File f, final FilenameFilter filter) {
    return ((String[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return f.list(filter);
        }
    }));
}
 
Example #26
Source File: AwoPatchReceiver.java    From atlas with Apache License 2.0 5 votes vote down vote up
private void doPatch(){
    try {
        File debugDirectory = new File(ATLAS_DEBUG_DIRECTORY);
        File[] bundles = debugDirectory.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                if (filename.endsWith(".so")) {
                    return true;
                }
                return false;
            }
        });
        if(bundles!=null && bundles.length>0){
            for(int x=0;x<bundles.length;x++){
                PackageInfo pkgInfo = RuntimeVariables.androidApplication.getPackageManager().getPackageArchiveInfo(bundles[0].getAbsolutePath(), 0);
                String packageName = pkgInfo.packageName;
                File debug_storage_bundle_dir = new File(RuntimeVariables.androidApplication.getExternalFilesDir("debug_storage"),packageName);
                if(!debug_storage_bundle_dir.exists()){
                    debug_storage_bundle_dir.mkdirs();
                }
                File targetPatchZip = new File(debug_storage_bundle_dir,"patch.zip");
                if(targetPatchZip.exists()){
                    targetPatchZip.delete();
                }
                bundles[0].renameTo(targetPatchZip);
                if(!targetPatchZip.exists()){
                    ApkUtils.copyInputStreamToFile(new FileInputStream(bundles[0]),targetPatchZip);
                }
                if(!targetPatchZip.exists()){
                    throw new IOException("move "+bundles[0]+"failed");
                }
            }
        }
    }catch(Throwable e){
        e.printStackTrace();
    }
}
 
Example #27
Source File: DatasetSinkIntegrationTests.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Test
public void testWritingSomething() throws IOException {
	TestPojo t1 = new TestPojo();
	t1.setId(1);
	t1.setTimestamp(systemTime + 10000);
	t1.setDescription("foo");
	sink.input().send(MessageBuilder.withPayload(t1).build());
	TestPojo t2 = new TestPojo();
	t2.setId(2);
	t2.setTimestamp(systemTime + 50000);
	t2.setDescription("x");
	sink.input().send(MessageBuilder.withPayload(t2).build());

	File testOutput = new File(testDir);
	assertTrue("Dataset path created", testOutput.exists());
	assertTrue("Dataset storage created",
			new File(testDir + File.separator + datasetOperations.getDatasetName(TestPojo.class)).exists());
	assertTrue("Dataset metadata created",
			new File(testDir + File.separator + datasetOperations.getDatasetName(TestPojo.class) +
					File.separator + ".metadata").exists());
	String year = new SimpleDateFormat("yyyy").format(systemTime);
	assertTrue("Dataset partition path created",
			new File(testDir + File.separator +
					datasetOperations.getDatasetName(TestPojo.class) + "/year=" + year).exists());
	File testDatasetFiles =
			new File(testDir + File.separator +
					datasetOperations.getDatasetName(TestPojo.class) + "/year=" + year);
	File[] files = testDatasetFiles.listFiles(new FilenameFilter() {
		@Override
		public boolean accept(File dir, String name) {
			if (name.endsWith(".avro")) {
				return true;
			}
			return false;
		}
	});
	assertTrue("Dataset data files created", files.length > 0);
}
 
Example #28
Source File: ContextImpl.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Try our best to migrate all files from source to target that match
 * requested prefix.
 *
 * @return the number of files moved, or -1 if there was trouble.
 */
private static int moveFiles(File sourceDir, File targetDir, final String prefix) {
    final File[] sourceFiles = FileUtils.listFilesOrEmpty(sourceDir, new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.startsWith(prefix);
        }
    });

    int res = 0;
    for (File sourceFile : sourceFiles) {
        final File targetFile = new File(targetDir, sourceFile.getName());
        Log.d(TAG, "Migrating " + sourceFile + " to " + targetFile);
        try {
            FileUtils.copyFileOrThrow(sourceFile, targetFile);
            FileUtils.copyPermissions(sourceFile, targetFile);
            if (!sourceFile.delete()) {
                throw new IOException("Failed to clean up " + sourceFile);
            }
            if (res != -1) {
                res++;
            }
        } catch (IOException e) {
            Log.w(TAG, "Failed to migrate " + sourceFile + ": " + e);
            res = -1;
        }
    }
    return res;
}
 
Example #29
Source File: FileUtils.java    From XKnife-Android with Apache License 2.0 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 #30
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");
		}	
	};
}