下面列出了怎么用org.apache.commons.io.filefilter.TrueFileFilter的API类实例代码及写法,或者点击链接到github查看源代码。
public DirectoryMonitor(String directorypath, long polling, String classname) {
this.directory = new File(directorypath);
this.trackedClassName = classname;
this.polling = polling;
if (!directory.isDirectory()) {
LOG.info("Monitored directory {} not existing - creating directory", directory.getAbsolutePath());
if (!this.directory.mkdirs()) {
throw new IllegalStateException("Monitored directory doesn't exist and cannot be created.");
}
}
// We observes all files.
FileAlterationObserver observer = new FileAlterationObserver(directory, TrueFileFilter.INSTANCE);
observer.checkAndNotify();
observer.addListener(new FileMonitor());
monitor = new FileAlterationMonitor(polling, observer);
}
private void getFileListing(File startingDirectory, GFileImpl currentRoot,
TaskMonitor monitor) {
Iterator<File> iterator = FileUtils.iterateFiles(startingDirectory, TrueFileFilter.INSTANCE,
TrueFileFilter.INSTANCE);
while (iterator.hasNext()) {
File f = iterator.next();
if (monitor.isCancelled()) {
break;
}
monitor.setMessage(f.getName());
GFileImpl gfile = GFileImpl.fromFilename(this, currentRoot, f.getName(),
f.isDirectory(), f.length(), null);
storeFile(gfile, f);
}
}
/**
* @author Mojang
* @reason Fix a bug
*/
@Overwrite
private void deleteOldServerResourcesPacks() {
try {
List<File> lvt_1_1_ = Lists.newArrayList(FileUtils.listFiles(this.dirServerResourcepacks, TrueFileFilter.TRUE, null));
Collections.sort(lvt_1_1_, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
int lvt_2_1_ = 0;
Iterator lvt_3_1_ = lvt_1_1_.iterator();
while(lvt_3_1_.hasNext()) {
File lvt_4_1_ = (File) lvt_3_1_.next();
if(lvt_2_1_++ >= 10) {
logger.info("Deleting old server resource pack " + lvt_4_1_.getName());
FileUtils.deleteQuietly(lvt_4_1_);
}
}
}catch(final Throwable e) {
e.printStackTrace();
}
}
/**
* @author Mojang
* @reason Fix a bug
*/
@Overwrite
private void deleteOldServerResourcesPacks() {
try {
List<File> lvt_1_1_ = Lists.newArrayList(FileUtils.listFiles(this.dirServerResourcepacks, TrueFileFilter.TRUE, null));
Collections.sort(lvt_1_1_, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
int lvt_2_1_ = 0;
Iterator lvt_3_1_ = lvt_1_1_.iterator();
while(lvt_3_1_.hasNext()) {
File lvt_4_1_ = (File) lvt_3_1_.next();
if(lvt_2_1_++ >= 10) {
logger.info("Deleting old server resource pack " + lvt_4_1_.getName());
FileUtils.deleteQuietly(lvt_4_1_);
}
}
}catch(final Throwable e) {
e.printStackTrace();
}
}
/**
* This method returns all Javafile-Paths of a project from a configuration.
*
* @param repoFolderPath
* @return allJavaFiles
* @throws IOException
*/
public List<String> getAllJavaFiles(String repoFolderPath) throws IOException {
// Init all java files path-list
List<String> allJavaFiles = new ArrayList<>();
// Get root folder of project
File dir = new File(repoFolderPath);
// Get paths to all java files of the project
List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (File file : files) {
if (file.getCanonicalPath().endsWith(".java")) {
allJavaFiles.add(file.getCanonicalPath());
}
}
return allJavaFiles;
}
private void importAttachments(File backupDir) {
File attachmentsDir = FileHelper.getAttachmentDir(this);
File backupAttachmentsDir = new File(backupDir, attachmentsDir.getName());
if (!backupAttachmentsDir.exists()) {
return;
}
Collection<File> list = FileUtils.listFiles(backupAttachmentsDir, FileFilterUtils.trueFileFilter(), TrueFileFilter.INSTANCE);
int imported = 0, size = list.size();
for (File file : list) {
try {
FileUtils.copyFileToDirectory(file, attachmentsDir, true);
mNotificationsHelper.setMessage(getString(R.string.text_attachment) + " " + imported++ + "/" + size).show();
} catch (IOException e) {
LogUtils.e("Error importing the attachment " + file.getName());
}
}
}
/**
* Verify the directory of the so file under the abi
*
* @param supportAbis
* @param removeSoFiles
* @param dirs
* @return
*/
public static Map<String, Multimap<String, File>> getAbiSoFiles(Set<String> supportAbis, Set<String> removeSoFiles,
List<File> dirs) {
Map<String, Multimap<String, File>> result = new HashMap<String, Multimap<String, File>>();
IOFileFilter filter = new NativeSoFilter(supportAbis, removeSoFiles);
for (File dir : dirs) {
Collection<File> files = FileUtils.listFiles(dir, filter, TrueFileFilter.TRUE);
for (File file : files) {
File parentFolder = file.getParentFile();
String parentName = parentFolder.getName();
String shortName = getSoShortName(file);
Multimap<String, File> maps = result.get(parentName);
if (null == maps) {
maps = HashMultimap.create(10, 3);
}
maps.put(shortName, file);
result.put(parentName, maps);
}
}
return result;
}
/**
* Initializes the file list information for the apk file
*
* @return
*/
protected static void prepareApkFileList(File folder, String prefixName, ApkFiles apkFiles) {
if (!folder.exists()) {
return;
}
// Gets information about the main bundle
Collection<File> files = FileUtils.listFiles(folder, new PureFileFilter(), TrueFileFilter.INSTANCE);
for (File file : files) {
if (file.isFile()) {
String relativePath = prefixName + File.separator + PathUtil.toRelative(folder, file.getAbsolutePath());
String md5;
if ("res".equals(prefixName)) {
md5 = getResMd5(file);
} else {
md5 = MD5Util.getFileMD5(file);
}
if (isImageFile(relativePath)) {
apkFiles.apkFileList.put(relativePath, md5);
}
apkFiles.finalApkFileList.put(relativePath, md5);
}
}
}
protected static void prepareApkFileList(File folder, String prefixName, String awbName, ApkFiles apkFiles) {
if (!folder.exists()) {
return;
}
// Gets information about the main bundle
Collection<File> files = FileUtils.listFiles(folder, new PureFileFilter(), TrueFileFilter.INSTANCE);
for (File file : files) {
if (file.isFile()) {
String relativePath = prefixName + File.separator + PathUtil.toRelative(folder, file.getAbsolutePath());
String md5 = MD5Util.getFileMD5(file);
if (isImageFile(relativePath)) {
if (null == apkFiles.apkFileList.getAwbs().get(awbName)) {
apkFiles.apkFileList.getAwbs().put(awbName, new HashMap<String, String>());
}
apkFiles.apkFileList.getAwbs().get(awbName).put(relativePath, md5);
}
if (null == apkFiles.finalApkFileList.getAwbs().get(awbName)) {
apkFiles.finalApkFileList.getAwbs().put(awbName, new HashMap<String, String>());
}
apkFiles.finalApkFileList.getAwbs().get(awbName).put(relativePath, md5);
}
}
}
/**
* 将指定文件夹下的文件转换为map
*
* @param folder
* @return
* @throws PatchException
*/
private Map<String, FileDef> getListFileMap(File folder) throws PatchException, IOException {
Map<String, FileDef> map = new HashMap<String, FileDef>();
if (!folder.exists() || !folder.isDirectory()) {
throw new PatchException("The input folder:" + folder.getAbsolutePath()
+ " does not existed or is not a directory!");
}
Collection<File> files = FileUtils.listFiles(folder, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (File file : files) {
String path = PathUtils.toRelative(folder, file.getAbsolutePath());
String md5 = MD5Util.getFileMD5String(file);
FileDef fileDef = new FileDef(md5, path, file);
map.put(path, fileDef);
}
return map;
}
private List<String> collectFiles(Collection<File> files) {
List<String> fileNames = new ArrayList<>();
ImmutableSet<String> extensions = ImmutableSet.copyOf(FILE_EXTENSIONS);
for (File file : files) {
if (file.isDirectory()) {
SuffixFileFilter suffixFileFilter = new SuffixFileFilter(toSuffixes(".", FILE_EXTENSIONS), IOCase.INSENSITIVE);
Collection<File> nestedFiles = FileUtils.listFiles(file, suffixFileFilter, TrueFileFilter.INSTANCE);
nestedFiles.stream().map(File::getPath).forEach(fileNames::add);
} else {
boolean allowedFileExtension = extensions.contains(FilenameUtils.getExtension(file.getName()).toLowerCase());
if (allowedFileExtension) {
fileNames.add(file.getPath());
}
}
}
return fileNames;
}
/**
* A new (accepted) file was deleted. This methods triggers the Java compilation.
*
* @param file the file
* @return {@literal true}
* @throws org.wisdom.maven.WatchingException thrown on compilation error. The thrown exception contains the file, line,
* character and reason of the compilation error.
*/
@Override
public boolean fileDeleted(final File file) throws WatchingException {
// Delete the associated class file.
// We delete more than required... but the inner class case is very tricky.
Collection<File> files = FileUtils.listFiles(classes, new IOFileFilter() {
@Override
public boolean accept(File test) {
String classname = FilenameUtils.getBaseName(test.getName());
String filename = FilenameUtils.getBaseName(file.getName());
return classname.equals(filename) || classname.startsWith(filename + "$");
}
@Override
public boolean accept(File dir, String name) {
return accept(new File(dir, name));
}
}, TrueFileFilter.INSTANCE);
for (File clazz : files) {
getLog().debug("Deleting " + clazz.getAbsolutePath() + " : " + clazz.delete());
}
compile();
return true;
}
@Override
public List<IPackage> getPackages() {
String masterProjectActionPath = JapiClient.getConfig().getPrefixPath() + JapiClient.getConfig().getProjectJavaPath() + JapiClient.getConfig().getPostfixPath() + "/" + JapiClient.getConfig().getActionReletivePath();
File actionFold = new File(masterProjectActionPath);
if (!actionFold.exists()) {
throw new JapiException(masterProjectActionPath + " fold not exists.");
}
final IOFileFilter dirFilter = FileFilterUtils.asFileFilter(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
Collection<File> folds = FileUtils.listFilesAndDirs(actionFold, dirFilter, TrueFileFilter.INSTANCE);
List<IPackage> packages = new ArrayList<>(folds.size());
for (File fold : folds) {
if (!fold.getAbsolutePath().equals(actionFold.getAbsolutePath())) {
PackageImpl packageImpl = new PackageImpl();
packageImpl.setPackageFold(fold);
packages.add(packageImpl);
}
}
return packages;
}
@Override
public List<MagicCardStock> listStocks(MagicCard mc, MagicCollection col,boolean editionStrict) throws SQLException {
List<MagicCardStock> st = new ArrayList<>();
File f = new File(directory, STOCKDIR);
for (File fstock : FileUtils.listFiles(f, new WildcardFileFilter("*" + IDGenerator.generate(mc)),TrueFileFilter.INSTANCE)) {
try {
MagicCardStock s = read(MagicCardStock.class, fstock);
if (s.getMagicCollection().getName().equals(col.getName()))
st.add(s);
} catch (Exception e) {
throw new SQLException(e);
}
}
return st;
}
private static Set<Path> getChildren(File f0, Path f0Base) {
return FileUtils.listFilesAndDirs(
f0,
TrueFileFilter.TRUE,
TrueFileFilter.TRUE
).stream(
).map(
File::getAbsolutePath
).map(
Paths::get
).map(p ->
f0Base.relativize(p)
).filter(p ->
!p.toString().isEmpty()
).collect(
Collectors.toSet()
);
}
public String getIndexPageURL() {
try {
File testOutputFolder = artifactsService.findArtifact(job.getIdentifier(), TEST_OUTPUT_FOLDER);
if (testOutputFolder.exists()) {
Collection<File> files = FileUtils.listFiles(testOutputFolder, new NameFileFilter("index.html"), TrueFileFilter.TRUE);
if (files.isEmpty()) {
return null;
}
File testIndexPage = files.iterator().next();
return getRestfulUrl(testIndexPage.getPath().substring(testIndexPage.getPath().indexOf(TEST_OUTPUT_FOLDER)));
}
} catch (Exception ignore) {
}
return null;
}
/**
* Visit all files recursively and calculate the hash of the file. Folders are also added to the result.
*
* @param root the root folder
* @return a map where the key is the relative file path to the root and the value is the hash
* @throws IOException if hashing fails
*/
public static Map<String, byte[]> visitFiles(File root) throws IOException {
Map<String, byte[]> digest = new HashMap<String, byte[]>();
Iterator<File> files = FileUtils.iterateFilesAndDirs(root, TrueFileFilter.TRUE, TrueFileFilter.TRUE);
while (files.hasNext()) {
File file = files.next();
if (file.equals(root)) {
// skip root folder
continue;
}
String path = FileUtil.relativize(root, file).toString();
byte[] hash = HashUtil.hash(file);
if (file.isDirectory()) {
digest.put(path + FileUtil.getFileSep(), hash);
} else {
digest.put(path, hash);
}
}
return digest;
}
private void processListing(File directory, TaskMonitor monitor) {
// WARNING: this method starts a new thread for every directory found
// in the extracted jar
Iterator<File> iterator = FileUtils.iterateFilesAndDirs(directory, FalseFileFilter.INSTANCE,
TrueFileFilter.INSTANCE);
while (iterator.hasNext()) {
File dir = iterator.next();
Task task = new JarDecompilerTask(dir, jarFile.getName() + ":" + getRelPath(dir));
TaskLauncher.launch(task);
}
}
public static void unlockLockedFilesOnQueue() {
final PropertyHandler propertyHandler = PropertyHandler.getInstance();
if (propertyHandler.hasProperty("MESSAGE_QUEUE_FOLDER")) {
String messageQueueFolderPath = propertyHandler.getProperty("MESSAGE_QUEUE_FOLDER");
File messageQueueFolder = new File(messageQueueFolderPath);
if (messageQueueFolder.exists()) {
String lockedFileSuffix = "_LOCK";
SuffixFileFilter suffixFileFilter = new SuffixFileFilter(lockedFileSuffix);
Integer numberOfMinutes = propertyHandler.getIntegerProperty("locked.file.retention", "2");
AgeFileFilter ageFileFilter = new AgeFileFilter(System.currentTimeMillis() - (numberOfMinutes * 60 * 1000));
Collection<File> lockedFiles = FileUtils.listFiles(messageQueueFolder, FileFilterUtils.and(suffixFileFilter, ageFileFilter), TrueFileFilter.INSTANCE);
for (File file : lockedFiles) {
String lockedFileName = file.getAbsolutePath();
File unlockedFile = new File(StringUtils.remove(lockedFileName, lockedFileSuffix));
file.setLastModified(new Date().getTime());
Boolean succesFullyUnlocked = file.renameTo(unlockedFile);
if (succesFullyUnlocked) {
LOG.info("File: " + lockedFileName + " successfully unlocked.");
}
}
} else {
LOG.info("No directory found on location: " + messageQueueFolderPath + ". No files unlocked");
}
} else {
LOG.info("No MESSAGE_QUEUE_FOLDER property in properties file. No files unlocked.");
}
}
/**
* Gets the list of HBase Common Avro schema strings from dir. It recursively
* searches dir to find files that end in .avsc to locate those strings.
*
* @param dir
* The dir to recursively search for schema strings
* @return The list of schema strings
*/
private List<String> getSchemaStringsFromDir(File dir) {
List<String> schemaStrings = new ArrayList<String>();
Collection<File> schemaFiles = FileUtils.listFiles(dir,
new SuffixFileFilter(".avsc"), TrueFileFilter.INSTANCE);
for (File schemaFile : schemaFiles) {
schemaStrings.add(getSchemaStringFromFile(schemaFile));
}
return schemaStrings;
}
public static void unlockLockedFilesOnQueue() {
final PropertyHandler propertyHandler = PropertyHandler.getInstance();
if (propertyHandler.hasProperty("MESSAGE_QUEUE_FOLDER")) {
String messageQueueFolderPath = propertyHandler.getProperty("MESSAGE_QUEUE_FOLDER");
File messageQueueFolder = new File(messageQueueFolderPath);
if (messageQueueFolder.exists()) {
String lockedFileSuffix = "_LOCK";
SuffixFileFilter suffixFileFilter = new SuffixFileFilter(lockedFileSuffix);
Integer numberOfMinutes = propertyHandler.getIntegerProperty("locked.file.retention", "2");
AgeFileFilter ageFileFilter = new AgeFileFilter(System.currentTimeMillis() - (numberOfMinutes * 60 * 1000));
Collection<File> lockedFiles = FileUtils.listFiles(messageQueueFolder, FileFilterUtils.and(suffixFileFilter, ageFileFilter), TrueFileFilter.INSTANCE);
for (File file : lockedFiles) {
String lockedFileName = file.getAbsolutePath();
File unlockedFile = new File(StringUtils.remove(lockedFileName, lockedFileSuffix));
file.setLastModified(new Date().getTime());
Boolean succesFullyUnlocked = file.renameTo(unlockedFile);
if (succesFullyUnlocked) {
LOG.info("File: " + lockedFileName + " successfully unlocked.");
}
}
} else {
LOG.info("No directory found on location: " + messageQueueFolderPath + ". No files unlocked");
}
} else {
LOG.info("No MESSAGE_QUEUE_FOLDER property in properties file. No files unlocked.");
}
}
public static void unlockLockedFilesOnQueue() {
final PropertyHandler propertyHandler = PropertyHandler.getInstance();
if (propertyHandler.hasProperty("MESSAGE_QUEUE_FOLDER")) {
String messageQueueFolderPath = propertyHandler.getProperty("MESSAGE_QUEUE_FOLDER");
File messageQueueFolder = new File(messageQueueFolderPath);
if (messageQueueFolder.exists()) {
String lockedFileSuffix = "_LOCK";
SuffixFileFilter suffixFileFilter = new SuffixFileFilter(lockedFileSuffix);
Integer numberOfMinutes = propertyHandler.getIntegerProperty("locked.file.retention", "2");
AgeFileFilter ageFileFilter = new AgeFileFilter(System.currentTimeMillis() - (numberOfMinutes * 60 * 1000));
Collection<File> lockedFiles = FileUtils.listFiles(messageQueueFolder, FileFilterUtils.and(suffixFileFilter, ageFileFilter), TrueFileFilter.INSTANCE);
for (File file : lockedFiles) {
String lockedFileName = file.getAbsolutePath();
File unlockedFile = new File(StringUtils.remove(lockedFileName, lockedFileSuffix));
file.setLastModified(new Date().getTime());
Boolean succesFullyUnlocked = file.renameTo(unlockedFile);
if (succesFullyUnlocked) {
LOG.info("File: " + lockedFileName + " successfully unlocked.");
}
}
} else {
LOG.info("No directory found on location: " + messageQueueFolderPath + ". No files unlocked");
}
} else {
LOG.info("No MESSAGE_QUEUE_FOLDER property in properties file. No files unlocked.");
}
}
public void deleteOldServerResourcesPacks(CallbackInfo callbackInfo, File dirServerResourcepacks) {
try {
FileUtils.listFiles(dirServerResourcepacks, TrueFileFilter.TRUE, null);
} catch (Exception e) {
callbackInfo.cancel();
}
}
/**
* 扫描由注解生成器生成到包 {@link Const#GEN_PKG_SERVICE} 里的初始化类
*/
private void scanDir(File dir, Set<String> initClasses) throws IOException {
File packageDir = new File(dir, INIT_SERVICE_DIR);
if (packageDir.exists() && packageDir.isDirectory()) {
Collection<File> files = FileUtils.listFiles(packageDir,
new SuffixFileFilter(SdkConstants.DOT_CLASS, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE);
for (File f : files) {
String className = trimName(f.getAbsolutePath(), dir.getAbsolutePath().length() + 1)
.replace(File.separatorChar, '.');
initClasses.add(className);
WMRouterLogger.info(" find ServiceInitClass: %s", className);
}
}
}
public static void main(String... args) throws Exception
{
Path inceptionDir = getInceptionDir();
Path webannoDir = inceptionDir.getParent().resolve("webanno");
Path outputDir = Paths.get(System.getProperty("user.dir")).resolve("target")
.resolve("doc-out");
Files.createDirectories(outputDir);
List<Path> modules = new ArrayList<>();
modules.addAll(getAsciiDocs(webannoDir));
modules.addAll(getAsciiDocs(inceptionDir));
FileUtils.deleteQuietly(outputDir.toFile());
Files.createDirectory(outputDir);
for (Path module : modules) {
System.out.printf("Including module: %s\n", module);
for (File f : FileUtils.listFiles(module.toFile(), TrueFileFilter.INSTANCE,
TrueFileFilter.INSTANCE)) {
Path p = f.toPath();
Path targetPath = f.toPath().subpath(module.toAbsolutePath().getNameCount()
, p.toAbsolutePath().getNameCount());
FileUtils.copyFile(f, outputDir.resolve("asciidoc").resolve(targetPath).toFile());
}
}
buildDoc("user-guide", outputDir);
buildDoc("developer-guide", outputDir);
buildDoc("admin-guide", outputDir);
System.out.printf("Documentation written to: %s\n", outputDir);
}
/**
* @param verbose
* boolean to activate verbose mode (show more traces).
* @param applicationDirectoryPath
* path of application directory (src or test).
*/
private void removeApplicationDirectoryIfEmpty(boolean verbose, String applicationDirectoryPath) {
try {
Collection<File> l = FileUtils.listFiles(new File(applicationDirectoryPath), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
if (l.isEmpty()) {
if (verbose) {
log.info("Empty directory, so remove application directory.");
}
FileUtils.deleteDirectory(new File(applicationDirectoryPath));
}
} catch (IOException e) {
log.debug("{} not revove because do not exist.", applicationDirectoryPath);
}
}
public void listFiles(String rootDir){
File dir = new File(rootDir);
List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
for (File file : files) {
System.out.println("file: " + file.getAbsolutePath());
}
}
/**
* @param localNativeLibrariesDirectory
* @param destinationDirectory
* @param supportAbis Type of architecture supported
* @param removeSoFiles
*/
public static void copyLocalNativeLibraries(final File localNativeLibrariesDirectory,
final File destinationDirectory, Set<String> supportAbis,
Set<String> removeSoFiles) {
sLogger.info("Copying existing native libraries from " + localNativeLibrariesDirectory + " to "
+ destinationDirectory);
try {
IOFileFilter filter = new NativeSoFilter(supportAbis, removeSoFiles);
// First, determine whether there is a file of the same name, if there is a discrepancy
Collection<File> files = FileUtils.listFiles(localNativeLibrariesDirectory, filter, TrueFileFilter.TRUE);
List<String> dumpFiles = new ArrayList<String>();
for (File file : files) {
String relativePath = getRelativePath(localNativeLibrariesDirectory, file);
File destFile = new File(destinationDirectory, relativePath);
if (destFile.exists()) {
String orgFileMd5 = MD5Util.getFileMD5(file);
String destFileMd5 = MD5Util.getFileMD5(destFile);
if (!orgFileMd5.equals(destFileMd5)) {
dumpFiles.add(file.getAbsolutePath() + " to " + destFile.getAbsolutePath());
}
}
}
if (dumpFiles.size() > 0) {
throw new RuntimeException("Copy native so error,duplicate file exist!:\n"
+ StringUtils.join(dumpFiles, "\n"));
}
FileUtils.copyDirectory(localNativeLibrariesDirectory, destinationDirectory, filter);
} catch (IOException e) {
throw new RuntimeException("Could not copy native dependency.", e);
}
}
/**
* Adds a directory to a {@link} with a directory prefix.
*
* @param jos ZipArchiver to use to archive the file.
* @param directory The directory to add.
* @param prefix An optional prefix for where in the Jar file the directory's contents should go.
*/
protected void addDirectory(JarOutputStream jos,
File directory,
String prefix) throws IOException {
if (directory != null && directory.exists()) {
Collection<File> files = FileUtils.listFiles(directory,
TrueFileFilter.INSTANCE,
TrueFileFilter.INSTANCE);
byte[] buf = new byte[8064];
for (File file : files) {
if (file.isDirectory()) {
continue;
}
String path = prefix +
"/" +
PathUtils.toRelative(directory, file.getAbsolutePath());
InputStream in = null;
try {
in = new FileInputStream(file);
ZipEntry fileEntry = new ZipEntry(path);
jos.putNextEntry(fileEntry);
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
jos.write(buf, 0, len);
}
// Complete the entry
jos.closeEntry();
in.close();
} finally {
IOUtils.closeQuietly(in);
}
}
}
}
@Override
public AttributedList<Path> list(final Path directory, final ListProgressListener listener) throws BackgroundException {
try {
final AttributedList<Path> children = new AttributedList<Path>();
final IRODSFileSystemAO fs = session.getClient();
final IRODSFile f = fs.getIRODSFileFactory().instanceIRODSFile(directory.getAbsolute());
if(!f.exists()) {
throw new NotfoundException(directory.getAbsolute());
}
for(File file : fs.getListInDirWithFileFilter(f, TrueFileFilter.TRUE)) {
final String normalized = PathNormalizer.normalize(file.getAbsolutePath(), true);
if(StringUtils.equals(normalized, directory.getAbsolute())) {
continue;
}
final PathAttributes attributes = new PathAttributes();
final ObjStat stats = fs.getObjStat(file.getAbsolutePath());
attributes.setModificationDate(stats.getModifiedAt().getTime());
attributes.setCreationDate(stats.getCreatedAt().getTime());
attributes.setSize(stats.getObjSize());
attributes.setChecksum(Checksum.parse(Hex.encodeHexString(Base64.decodeBase64(stats.getChecksum()))));
attributes.setOwner(stats.getOwnerName());
attributes.setGroup(stats.getOwnerZone());
children.add(new Path(directory, PathNormalizer.name(normalized),
file.isDirectory() ? EnumSet.of(Path.Type.directory) : EnumSet.of(Path.Type.file),
attributes));
listener.chunk(directory, children);
}
return children;
}
catch(JargonException e) {
throw new IRODSExceptionMappingService().map("Listing directory {0} failed", e, directory);
}
}