下面列出了怎么用java.nio.file.FileVisitResult的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
String filePath = file.toString().replaceAll("\\\\", "/");
filePath = filePath.replace(prefix, "");
Optional<app.jweb.file.domain.File> optional = fileService.findByPath(filePath);
if (!optional.isPresent()) {
File realFile = file.toFile();
String directoryPath = parent(filePath);
CreateFileRequest createFileRequest = new CreateFileRequest();
createFileRequest.directoryId = map.get(directoryPath).id;
createFileRequest.path = filePath;
createFileRequest.length = realFile.length();
createFileRequest.fileName = realFile.getName();
createFileRequest.requestBy = "synchronized";
fileService.create(createFileRequest);
}
return FileVisitResult.CONTINUE;
}
@AfterMethod
public void tearDown() throws IOException {
Files.delete(zipFile);
Files.walkFileTree(
tempDir,
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 e) throws IOException {
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw e;
}
}
});
}
private static void deletePath(final Path path) throws IOException {
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
Files.deleteIfExists(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
Files.deleteIfExists(dir);
return FileVisitResult.CONTINUE;
}
});
} else {
Files.deleteIfExists(path);
}
}
EurostagDDB(List<Path> ddbDirs) throws IOException {
for (Path ddbDir : ddbDirs) {
ddbDir = readSymbolicLink(ddbDir);
if (!Files.exists(ddbDir) && !Files.isDirectory(ddbDir)) {
throw new IllegalArgumentException(ddbDir + " must exist and be a dir");
}
Files.walkFileTree(ddbDir, 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();
Path tmpfile = readSymbolicLink(file);
if (Files.isDirectory(tmpfile)) {
Files.walkFileTree(tmpfile, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, this);
} else if (Files.isRegularFile(tmpfile) && fileName.endsWith(".tg")) {
String key = fileName.substring(0, fileName.length() - 3);
if (generators.containsKey(key)) {
LOGGER.warn("the processing has detected that the file {} is present in {} and {}", fileName, tmpfile, generators.get(key));
}
generators.put(key, tmpfile);
}
return super.visitFile(file, attrs);
}
});
}
}
@Before
public void init() throws IOException {
Path directory = Paths.get(LOCAL_REPO);
if (Files.exists(directory)) {
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;
}
});
}
this.cut = new TakeDown(LOCAL_REPO, "git://localhost:4242/");
}
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;
}
});
}
@Override
public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
System.out.println("Move directory: " + (Path) dir);
Path newDir = moveTo.resolve(moveFrom.relativize((Path) dir));
try {
Files.copy((Path) dir, newDir, REPLACE_EXISTING, COPY_ATTRIBUTES);
time = Files.getLastModifiedTime((Path) dir);
} catch (IOException e) {
System.err.println("Unable to move " + newDir + " [" + e + "]");
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
/**
* Delete all files under a target directory
* @param path: folder containing spec files
* @throws IOException
*/
public void cleanDir(String path) throws IOException {
Path directory = Paths.get(path);
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;
}
});
}
@After
public void tearDown() throws Exception {
super.tearDown();
Files.walkFileTree(output, 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;
}
});
output = null;
}
@Override
public void copyDir(ProjectFilesystem filesystem, Path srcDir, Path destDir, Predicate<Path> pred)
throws IOException {
// Remove existing contents if any.
if (filesystem.exists(destDir)) {
filesystem.deleteRecursivelyIfExists(destDir);
}
filesystem.mkdirs(destDir);
filesystem.walkRelativeFileTree(
srcDir,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path srcPath, BasicFileAttributes attributes)
throws IOException {
if (pred.test(srcPath)) {
Path destPath = destDir.resolve(srcDir.relativize(srcPath));
filesystem.createParentDirs(destPath);
filesystem.copy(srcPath, destPath, CopySourceMode.FILE);
}
return FileVisitResult.CONTINUE;
}
});
}
@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());
}
}
private void addDirectories(File parent, Set<String> packages)
throws IOException {
Path root = parent.toPath();
Files.walkFileTree(parent.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
File file = dir.toFile();
if (file.isDirectory()) {
Path relative = root.relativize(file.toPath());
packages.add(relative.toString().replace(File.separatorChar,
'.'));
}
return super.postVisitDirectory(dir, exc);
}
});
}
public static void generateDummyPlatform(Path destination, String version) throws IOException, URISyntaxException {
Path targetZip = destination.resolve(String.format("hybris-commerce-suite-%s.zip", version));
Map<String, String> env = new HashMap<>();
env.put("create", "true");
try (FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + targetZip.toUri().toString()), env, null)) {
Path sourceDir = Paths.get(TestUtils.class.getResource("/dummy-platform").toURI());
Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relative = sourceDir.relativize(file);
if (relative.getParent() != null) {
Path path = zipfs.getPath(relative.getParent().toString());
Files.createDirectories(path);
}
Path target = zipfs.getPath(relative.toString());
Files.copy(file, target);
return super.visitFile(file, attrs);
}
});
String build = String.format("version=%s\n", version);
Path buildNumber = zipfs.getPath("hybris", "bin", "platform", "build.number");
Files.write(buildNumber, build.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}
}
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]));
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
// ルートディレクトリかチェック
if (this.baseDir.equals(dir)) {
return FileVisitResult.CONTINUE;
}
// 年月のフォルダかチェック
String dirName = dir.getFileName().toString();
if (!isExpectedDirectoryName(dirName)) {
return FileVisitResult.SKIP_SUBTREE;
}
// 年月部分を比較
if (dirName.compareTo(this.expired.substring(0, dirName.length())) > 0) {
return FileVisitResult.SKIP_SUBTREE;
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attr) throws IOException {
if(PathUtils.isFileHidden(path)){
return FileVisitResult.CONTINUE;
}
if (throwCreates) {
eventManager.onLocalFileCreated(path);
} else {
if (Files.isDirectory(path)) {
FolderComposite newFolder = new FolderComposite(path, false);
newFolder.setIsSynchronized(true);
fileTree.putComponent(path, newFolder);
} else {
FileLeaf newFile = new FileLeaf(path, false);
newFile.setIsSynchronized(true);
fileTree.putComponent(path, newFile);
}
}
return FileVisitResult.CONTINUE;
}
public static void cleanFiles() {
Path directory = Paths.get("target/test-files/");
try {
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;
}
});
} catch (Exception ignore) {
}
}
@Before
@After
public void cleanupStorage() throws IOException {
if (Files.exists(PATH)) {
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;
}
});
}
}
protected static void deleteRecursively(final Path path) throws IOException {
if (Files.exists(path)) {
if (Files.isDirectory(path)) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
Files.deleteIfExists(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
Files.deleteIfExists(dir);
return FileVisitResult.CONTINUE;
}
});
} else {
Files.deleteIfExists(path);
}
}
}
/**
* Empties an existing directory, by recursively removing all it's siblings, regular files and directories. Accepts
* only existing directories, and when returns, it's guaranteed that passed in directory will be emptied (will
* have no siblings, not counting OS specific ones, will be "empty" as per current OS is empty defined).
*/
public static void empty(final Path dir) throws IOException {
validateDirectory(dir);
Files.walkFileTree(dir, DEFAULT_FILE_VISIT_OPTIONS, Integer.MAX_VALUE,
new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile(final Path f, final BasicFileAttributes attrs) throws IOException {
Files.delete(f);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(final Path d, final IOException exc) throws IOException {
if (exc != null) {
throw exc;
}
else if (dir != d) {
Files.delete(d);
}
return FileVisitResult.CONTINUE;
}
}
);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!attrs.isRegularFile()) return CONTINUE;
if (partOfNameCheck && file.getFileName().toString().indexOf(this.partOfName) == -1)
return CONTINUE;
if (minSizeCheck && attrs.size() < minSize)
return CONTINUE;
if (maxSizeCheck && attrs.size() > maxSize)
return CONTINUE;
if (partOfContentCheck && new String(Files.readAllBytes(file)).indexOf(partOfContent) == -1)
return CONTINUE;
foundFiles.add(file);
return CONTINUE;
}
/**
* @return true if all files in the {@link org.mycore.datamodel.ifs2.MCRDirectory} appears in the fileGroup
*/
public static boolean isComplete(final FileGrp fileGroup, MCRPath rootDir) {
final AtomicBoolean complete = new AtomicBoolean(true);
try {
Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (!file.getFileName().toString().equals(MCRMetsSave.getMetsFileName())) {
MCRPath mcrPath = MCRPath.toMCRPath(file);
String path;
try {
path = MCRXMLFunctions
.encodeURIPath(mcrPath.getOwnerRelativePath().substring(1), true);//remove leading '/'
} catch (URISyntaxException e) {
throw new IOException(e);
}
if (!fileGroup.contains(path)) {
LOGGER.warn("{} does not appear in {}!", path, mcrPath.getOwner());
complete.set(false);
return FileVisitResult.TERMINATE;
}
}
return super.visitFile(file, attrs);
}
});
} catch (Exception ex) {
LOGGER.error("Error while validating mets", ex);
return false;
}
return complete.get();
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
//end matching attributes set by ignorepath
wg.endTag();
attributes.pop();
return CONTINUE;
}
/**
* This methods checks all provided files to be correct WAL segment.
* Header record and its position is checked. WAL position is used to determine real index.
* File index from file name is ignored.
*
* @param iteratorParametersBuilder IteratorParametersBuilder.
* @return list of file descriptors with checked header records, having correct file index is set
*/
public List<FileDescriptor> resolveWalFiles(
IteratorParametersBuilder iteratorParametersBuilder
) {
File[] filesOrDirs = iteratorParametersBuilder.filesOrDirs;
if (filesOrDirs == null || filesOrDirs.length == 0)
return Collections.emptyList();
final FileIOFactory ioFactory = iteratorParametersBuilder.ioFactory;
final TreeSet<FileDescriptor> descriptors = new TreeSet<>();
for (File file : filesOrDirs) {
if (file.isDirectory()) {
try {
walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
@Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
addFileDescriptor(path.toFile(), ioFactory, descriptors);
return FileVisitResult.CONTINUE;
}
});
}
catch (IOException e) {
U.error(log, "Failed to walk directories from root [" + file + "]. Skipping this directory.", e);
}
continue;
}
addFileDescriptor(file, ioFactory, descriptors);
}
return new ArrayList<>(descriptors);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
if (file.toString().toLowerCase().endsWith(".java")) {
this.javaFiles.add(file.toString());
}
return FileVisitResult.CONTINUE;
}
public static void deleteRecursively(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;
}
});
}
void processSection(JmodOutputStream out, Section section, Path path)
throws IOException
{
Files.walkFileTree(path, Set.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException
{
Path relPath = path.relativize(file);
if (relPath.toString().equals(MODULE_INFO)
&& !Section.CLASSES.equals(section))
warning("warn.ignore.entry", MODULE_INFO, section);
if (!relPath.toString().equals(MODULE_INFO)
&& !matches(relPath, excludes)) {
try (InputStream in = Files.newInputStream(file)) {
out.writeEntry(in, section, relPath.toString());
} catch (IOException x) {
if (x.getMessage().contains("duplicate entry")) {
warning("warn.ignore.duplicate.entry",
relPath.toString(), section);
return FileVisitResult.CONTINUE;
}
throw x;
}
}
return FileVisitResult.CONTINUE;
}
});
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Path relativePath = baseDir.relativize(file);
byte[] content = Files.readAllBytes(file);
if (isJavaClass(relativePath)) {
visitClass(relativePath, content);
} else {
visitResource(relativePath, content);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path path, IOException exception) throws IOException {
if (exception != null) {
Log.error(exception);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException ioe) throws IOException {
Path newDir = moveTo.resolve(moveFrom.relativize((Path) dir));
try {
Files.setLastModifiedTime(newDir, time);
Files.delete((Path) dir);
} catch (IOException e) {
System.err.println("Unable to copy all attributes to: " + newDir + " [" + e + "]");
}
return FileVisitResult.CONTINUE;
}