下面列出了怎么用java.nio.file.SimpleFileVisitor的API类实例代码及写法,或者点击链接到github查看源代码。
private void remove(File base) throws IOException{
if (!base.exists()) {
return;
}
Files.walkFileTree(base.toPath(), new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
public static Map<String, byte[]> getFilesGroupByFilename(String pathName) throws IOException {
if (pathName == null) {
throw new IOException("Path is null");
}
if (!new File(pathName).exists()) {
throw new IOException("Path " + pathName + " is not exists");
}
Map<String, byte[]> filesGroup = new HashMap<>();
File path = new File(pathName);
Files.walkFileTree(Paths.get(path.toURI()), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
filesGroup.put(file.toFile().getName(), Files.readAllBytes(file));
return super.visitFile(file, attrs);
}
});
return filesGroup;
}
private static List<String> listClasses(Path base)
throws IOException
{
ImmutableList.Builder<String> list = ImmutableList.builder();
walkFileTree(base, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
{
if (file.getFileName().toString().endsWith(CLASS_FILE_SUFFIX)) {
String name = file.subpath(base.getNameCount(), file.getNameCount()).toString();
list.add(javaName(name.substring(0, name.length() - CLASS_FILE_SUFFIX.length())));
}
return FileVisitResult.CONTINUE;
}
});
return list.build();
}
/**
* Delete the supplied {@link File} - for directories,
* recursively delete any nested directories or files as well.
* @param root the root {@code File} to delete
* @return {@code true} if the {@code File} existed and was deleted,
* or {@code false} it it did not exist
* @throws IOException in the case of I/O errors
* @since 5.0
*/
public static boolean deleteRecursively(@Nullable Path root) throws IOException {
if (root == null) {
return false;
}
if (!Files.exists(root)) {
return false;
}
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
return true;
}
public void scanTree(Path base) throws IOException {
PathLoader loader = new PathLoader(base, bootLoader);
loaders.add(loader);
try {
Files.walkFileTree(base, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.toString().endsWith(".class")) {
String className = base.relativize(file).toString();
className = className.replace('\\', '/');
className = className.substring(0, className.length() - 6);
registerClass(className, loader);
}
return FileVisitResult.CONTINUE;
}
});
} catch (NoSuchFileException e) {
// Skip invalid classpath entry
}
}
public void compress(final ZipOutputStream outputStream, final Path sourceDir, final Path toCompress, final String removePiece) throws IOException {
Files.walkFileTree(toCompress, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
try {
final Path targetFile = sourceDir.relativize(file);
final String target = toZipEntryName(targetFile, removePiece);
logger.debug("Adding file to zip: " + target);
outputStream.putNextEntry(new ZipEntry(target));
final byte[] bytes = Files.readAllBytes(file);
outputStream.write(bytes, 0, bytes.length);
outputStream.closeEntry();
} catch (final IOException e) {
logger.error("Failed to write to zip.", e);
}
return FileVisitResult.CONTINUE;
}
});
}
@Override
public void close() throws Exception {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* This method is primarily used to give visual confirmation that a test case
* generated files when the compilation succeeds and so generates no other output,
* such as error messages.
*/
List<Path> showFiles(Path dir) throws IOException {
List<Path> files = new ArrayList<>();
Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (Files.isRegularFile(file)) {
out.println("Found " + file);
files.add(file);
}
return FileVisitResult.CONTINUE;
}
});
return files;
}
/**
* Delete the supplied {@link File} - for directories,
* recursively delete any nested directories or files as well.
* @param root the root {@code File} to delete
* @return {@code true} if the {@code File} existed and was deleted,
* or {@code false} it it did not exist
* @throws IOException in the case of I/O errors
* @since 5.0
*/
public static boolean deleteRecursively(@Nullable Path root) throws IOException {
if (root == null) {
return false;
}
if (!Files.exists(root)) {
return false;
}
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
return true;
}
@After
public void tearDown() throws Exception
{
Files.walkFileTree(_tmpDir,
new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
throws IOException
{
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
throws IOException
{
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
this.archivePath = archivePath;
if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);
FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
Assert.checkNonNull(jarFSProvider, "should have been caught before!");
this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
} else {
this.fileSystem = FileSystems.newFileSystem(archivePath, null);
}
packages = new HashMap<>();
for (Path root : fileSystem.getRootDirectories()) {
Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (isValid(dir.getFileName())) {
packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.SKIP_SUBTREE;
}
}
});
}
}
/**
* Determine the number of unprocessed flag files in the flag directory
*
* @param fc
* @return the flag found for this ingest pool
*/
private int countFlagFileBacklog(final FlagDataTypeConfig fc) {
final MutableInt fileCounter = new MutableInt(0);
final FileFilter fileFilter = new WildcardFileFilter("*_" + fc.getIngestPool() + "_" + fc.getDataName() + "_*.flag");
final FileVisitor<java.nio.file.Path> visitor = new SimpleFileVisitor<java.nio.file.Path>() {
@Override
public FileVisitResult visitFile(java.nio.file.Path path, BasicFileAttributes attrs) throws IOException {
if (fileFilter.accept(path.toFile())) {
fileCounter.increment();
}
return super.visitFile(path, attrs);
}
};
try {
Files.walkFileTree(Paths.get(fmc.getFlagFileDirectory()), visitor);
} catch (IOException e) {
// unable to get a flag count....
log.error("Unable to get flag file count", e);
return -1;
}
return fileCounter.intValue();
}
public void compress(final ZipOutputStream outputStream, final Path sourceDir, final Path toCompress, final File out, final String removePiece) throws IOException {
Files.walkFileTree(toCompress, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attributes) {
try {
final Path targetFile = sourceDir.relativize(file);
final String target = toZipEntryName(targetFile, removePiece);
logger.debug("Adding file to zip: " + target);
outputStream.putNextEntry(new ZipEntry(target));
final byte[] bytes = Files.readAllBytes(file);
outputStream.write(bytes, 0, bytes.length);
outputStream.closeEntry();
} catch (final IOException e) {
logger.error("Failed to write to zip.", e);
}
return FileVisitResult.CONTINUE;
}
});
}
/**
* Delete a directory and all files contained within it.
*
* @param directory The directory to delete.
* @throws IOException If an I/O error occurs.
*/
public static void deleteRecursively(Path directory) throws IOException {
checkNotNull(directory);
walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Recursively delete the directory root and all its contents
* @param root Root directory to be deleted
*/
public static void deleteDirectory(Path root) throws IOException {
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
static void deleteDirectory(File directory) throws IOException {
if (!directory.exists())
return;
Path path = Paths.get(directory.getPath());
SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(path, visitor);
}
@Override
public Set<File> findConfigurableLocations(File root, IProgressMonitor monitor) {
Set<File> files = new HashSet<>();
try {
Files.walkFileTree(root.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.endsWith(GlobalConstants.PUBSPEC_YAML)) {
files.add(file.toFile().getParentFile());
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
LOG.log(DartLog.createError("Couldn't walk children directories", e)); //$NON-NLS-1$
}
return files;
}
@Before
public void before() throws Exception {
// Clean up old files.
if (Files.isDirectory(archiveDir.toPath())) {
Files.walkFileTree(archiveDir.toPath(), new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
}
// Create original flow.xml.gz
Files.createDirectories(flowFile.getParentFile().toPath());
try (OutputStream os = Files.newOutputStream(flowFile.toPath(),
StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
// 10 bytes.
os.write("0123456789".getBytes());
}
}
public void readTrustStore(Path dir) throws IOException, CertificateException {
if (!IOHelper.isDir(dir)) {
Files.createDirectories(dir);
try (OutputStream outputStream = IOHelper.newOutput(dir.resolve("GravitCentralRootCA.crt"));
InputStream inputStream = IOHelper.newInput(IOHelper.getResourceURL("pro/gravit/launchserver/defaults/GravitCentralRootCA.crt"))) {
IOHelper.transfer(inputStream, outputStream);
}
}
List<X509Certificate> certificates = new ArrayList<>();
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
IOHelper.walk(dir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toFile().getName().endsWith(".crt")) {
try (InputStream inputStream = IOHelper.newInput(file)) {
certificates.add((X509Certificate) certFactory.generateCertificate(inputStream));
} catch (CertificateException e) {
throw new IOException(e);
}
}
return super.visitFile(file, attrs);
}
}, false);
trustManager = new LauncherTrustManager(certificates.toArray(new X509Certificate[0]));
}
private void cleanTraces() {
Path path = null;
try {
path = FileSystems.getDefault().getPath(BSql.OLD_BSQL_BASE_FOLDER);
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException ex) {
logger.error("Failed to delete old copy of data. You may manually delete the folder located at: " + path.toAbsolutePath().toString());
java.util.logging.Logger.getLogger(Version1to2.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public void run() {
try {
Files.walkFileTree(iconsFolder, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
final String fileName = file.getFileName().toString();
if (fileName.endsWith(".svg")) {
final Path svg = file
.getParent()
.resolve(fileName.substring(0, fileName.length() - ".svg".length()) + "_icon32.png");
if (!Files.exists(svg)) {
createPng(file, svg);
log.info("Created " + svg);
}
}
return super.visitFile(file, attrs);
}
});
} catch (final IOException e) {
throw new IllegalStateException(e);
}
}
private void collectKnownPaths(Path resource, Set<String> knownPaths) {
try {
Files.walkFileTree(resource, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path p, BasicFileAttributes attrs)
throws IOException {
String file = resource.relativize(p).toString();
if (file.equals("index.html") || file.equals("index.htm")) {
knownPaths.add("/");
}
if (!file.startsWith("/")) {
file = "/" + file;
}
// Windows has a backslash
file = file.replace('\\', '/');
knownPaths.add(file);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private void cleanupTempFiles() throws IOException {
if (tmpPath == null) {
return;
}
Files.walkFileTree(tmpPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
private static void deleteDir(Path directory) throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
public void delete() {
FileVisitor<Path> fileVisitor = new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
};
try {
Files.walkFileTree(dir, fileVisitor);
} catch (IOException e) {
throw new ResourceException("failed to delete dir, path={}", dir, e);
}
}
static void indexDocs(final IndexWriter writer, Path path) throws IOException {
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
try {
indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
} catch (IOException ignore) {
}
return FileVisitResult.CONTINUE;
}
}
);
} else {
indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis());
}
}
public void testWalkFileTreeMultiple() throws IOException {
final int ITERATIONS = 1000;
Path newDirectory = WALKFILETREE_FILE_DIR;
for (int counter=0; counter< ITERATIONS; counter++) {
HangNotifier.ping();
final List<Path> visitorFiles = new LinkedList<Path>();
// Check that we keep returning the same set of files!
Files.walkFileTree(newDirectory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) {
if (path.toString().endsWith(".txt")) {
visitorFiles.add(path);
}
return FileVisitResult.CONTINUE;
}
});
if(!ReiserSpotter.getIsReiser()){
assertEquals("Wrong number of files walked on iteration " + counter, NUMBER_OF_FILES, visitorFiles.size());
}
}
}
public Set<Path> getMapFolders(final Logger logger) throws IOException {
final Set<Path> mapFolders = new HashSet<>();
for(Path root : getRootPaths()) {
int depth = "".equals(root.toString()) ? 0 : Iterables.size(root);
Files.walkFileTree(getPath().resolve(root), ImmutableSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth - depth, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if(!isExcluded(dir)) {
if(MapFolder.isMapFolder(dir)) {
mapFolders.add(dir);
}
return FileVisitResult.CONTINUE;
} else {
logger.fine("Skipping excluded path " + dir);
return FileVisitResult.SKIP_SUBTREE;
}
}
});
}
return mapFolders;
}
static void resolveConfig(Environment env, final Settings.Builder settingsBuilder) {
try {
Files.walkFileTree(env.configFile(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
String fileName = file.getFileName().toString();
if (fileName.startsWith("logging.")) {
for (String allowedSuffix : ALLOWED_SUFFIXES) {
if (fileName.endsWith(allowedSuffix)) {
loadConfig(file, settingsBuilder);
break;
}
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException ioe) {
throw new ElasticsearchException("Failed to load logging configuration", ioe);
}
}
public void compact() throws IOException {
// making the cache using a local repository generates a lot of files
// we don't need, including duplicated jars for -SNAPSHOT versions so
// we remove any file from the cache where the name doesn't include
// the parent folder name within it, which leaves us the main jar, the
// pom.xml and the -creole.jar plus some .sha1 files
Files.walkFileTree(head.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String filename = file.getFileName().toString();
if((!filename.endsWith(".jar") && !filename.endsWith(".pom")) ||
!filename.contains(file.getParent().getFileName().toString())) {
java.nio.file.Files.delete(file);
}
return FileVisitResult.CONTINUE;
}
});
}