Java Code Examples for java.nio.file.Files#isDirectory()

The following examples show how to use java.nio.file.Files#isDirectory() . 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: WatchServiceFileWatcher.java    From mirror with Apache License 2.0 6 votes vote down vote up
private void onChangedPath(BlockingQueue<Update> queue, Path path) throws IOException, InterruptedException {
  // always recurse into directories so that even if we're excluding target/*,
  // if we are including target/scala-2.10/src_managed, then we can match those
  // paths even though we're ignoring some of the cruft around it
  try {
    if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
      onChangedDirectory(queue, path);
    } else if (Files.isSymbolicLink(path)) {
      onChangedSymbolicLink(queue, path);
    } else {
      onChangedFile(queue, path);
    }
  } catch (NoSuchFileException | FileNotFoundException e) {
    // if a file gets deleted while getting the mod time/etc., just ignore it
  }
}
 
Example 2
Source File: OutputConsumerPath.java    From tiny-remapper with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void accept(String clsName, byte[] data) {
	if (classNameFilter != null && !classNameFilter.test(clsName)) return;

	try {
		if (lock != null) lock.lock();
		if (closed) throw new IllegalStateException("consumer already closed");

		Path dstFile = dstDir.resolve(clsName + classSuffix);

		if (isJarFs && Files.exists(dstFile)) {
			if (Files.isDirectory(dstFile)) throw new FileAlreadyExistsException("dst file "+dstFile+" is a directory");

			Files.delete(dstFile); // workaround for sporadic FileAlreadyExistsException (Files.write should overwrite, jdk bug?)
		}

		createParentDirs(dstFile);
		Files.write(dstFile, data);
	} catch (IOException e) {
		throw new RuntimeException(e);
	} finally {
		if (lock != null) lock.unlock();
	}
}
 
Example 3
Source File: Creator.java    From jmbe with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Deletes the compiled interface classes from the output directory
 *
 * @param output
 * @throws IOException
 */
public static void deleteInterfaceClasses(Path output) throws IOException
{
    Path iface = output.resolve("jmbe").resolve("iface");

    if(Files.exists(iface) && Files.isDirectory(iface))
    {
        DirectoryStream<Path> stream = Files.newDirectoryStream(iface);
        stream.forEach(file -> {
            try
            {
                Files.delete(file);
            }
            catch(IOException ioe)
            {
                System.out.println("Error deleteing interface class file: " + file.toString());
                ioe.printStackTrace();
                System.exit(EXIT_CODE_IO_ERROR);
            }
        });
        Files.delete(iface);
    }
}
 
Example 4
Source File: SdkToolsLocator.java    From bundletool with Apache License 2.0 5 votes vote down vote up
/** Tries to locate adb utility under "platform-tools". */
private Optional<Path> locateAdbInSdkDir(SystemEnvironmentProvider systemEnvironmentProvider) {
  Optional<String> sdkDir = systemEnvironmentProvider.getVariable(ANDROID_HOME_VARIABLE);
  if (!sdkDir.isPresent()) {
    return Optional.empty();
  }

  Path platformToolsDir = fileSystem.getPath(sdkDir.get(), "platform-tools");
  if (!Files.isDirectory(platformToolsDir)) {
    return Optional.empty();
  }

  // Expecting to find one entry.
  PathMatcher adbPathMatcher = fileSystem.getPathMatcher(ADB_SDK_GLOB);
  try (Stream<Path> pathStream =
      Files.find(
          platformToolsDir,
          /* maxDepth= */ 1,
          (path, attributes) -> adbPathMatcher.matches(path) && Files.isExecutable(path))) {
    return pathStream.findFirst();
  } catch (IOException e) {
    throw CommandExecutionException.builder()
        .withCause(e)
        .withInternalMessage("Error while trying to locate adb in SDK dir '%s'.", sdkDir)
        .build();
  }
}
 
Example 5
Source File: DirectoryManagerImpl.java    From Wikidata-Toolkit with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a directory at the given path if it does not exist yet and if the
 * directory manager was not configured for read-only access.
 *
 * @param path
 * @throws IOException
 *             if it was not possible to create a directory at the given
 *             path
 */
void createDirectory(Path path) throws IOException {
	if (Files.exists(path) && Files.isDirectory(path)) {
		return;
	}

	if (this.readOnly) {
		throw new FileNotFoundException(
				"The requested directory \""
						+ path.toString()
						+ "\" does not exist and we are in read-only mode, so it cannot be created.");
	}

	Files.createDirectory(path);
}
 
Example 6
Source File: ClassFileReader.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a ClassFileReader instance of a given path.
 */
public static ClassFileReader newInstance(Path path) throws IOException {
    if (!Files.exists(path)) {
        throw new FileNotFoundException(path.toString());
    }

    if (Files.isDirectory(path)) {
        return new DirectoryReader(path);
    } else if (path.getFileName().toString().endsWith(".jar")) {
        return new JarFileReader(path);
    } else {
        return new ClassFileReader(path);
    }
}
 
Example 7
Source File: ModuleReferences.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
ExplodedModuleReader(Path dir) {
    this.dir = dir;

    // when running with a security manager then check that the caller
    // has access to the directory.
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        boolean unused = Files.isDirectory(dir);
    }
}
 
Example 8
Source File: JShellTool.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean checkValidPathEntry(Path p, String context, boolean isModulePath) {
    if (!Files.exists(p)) {
        msg("jshell.err.file.not.found", context, p);
        failed = true;
        return false;
    }
    if (Files.isDirectory(p)) {
        // if module-path, either an exploded module or a directory of modules
        return true;
    }

    String name = p.getFileName().toString();
    int lastDot = name.lastIndexOf(".");
    if (lastDot > 0) {
        switch (name.substring(lastDot)) {
            case ".jar":
                return true;
            case ".jmod":
                if (isModulePath) {
                    return true;
                }
        }
    }
    msg("jshell.err.arg", context, p);
    failed = true;
    return false;
}
 
Example 9
Source File: OFDDoc.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 在指定路径位置上创建一个OFD文件
 *
 * @param outPath OFD输出路径
 */
public OFDDoc(Path outPath) {
    this();
    if (outPath == null) {
        throw new IllegalArgumentException("OFD文件存储路径(outPath)为空");
    }
    if (Files.isDirectory(outPath)) {
        throw new IllegalArgumentException("OFD文件存储路径(outPath)不能是目录");
    }
    this.outPath = outPath;
}
 
Example 10
Source File: ExecutionEnvironment.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void verifySymLinks(String bindir) throws IOException {
    File binDir = new File(bindir);
    System.err.println("verifying links in: " + bindir);
    File isaDir = new File(binDir, getArch()).getAbsoluteFile();
    if (!isaDir.exists()) {
        throw new RuntimeException("dir: " + isaDir + " does not exist");
    }
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(binDir.toPath())) {
        for (Path p : ds) {
            if (symlinkExcludes.matcher(p.toString()).matches() ||
                    Files.isDirectory(p, NOFOLLOW_LINKS)) {
                continue;
            }
            Path link = new File(isaDir, p.getFileName().toString()).toPath();
            if (Files.isSymbolicLink(link)) {
                Path target = Files.readSymbolicLink(link);
                if (target.startsWith("..") && p.endsWith(target.getFileName())) {
                    // System.out.println(target + " OK");
                    continue;
                }
                System.err.println("target:" + target);
                System.err.println("file:" + p);
            }
            throw new RuntimeException("could not find link to " + p);
        }
    }

}
 
Example 11
Source File: LocalFileReader.java    From protostuff-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Check that all elements in the list exist and are directories.
 * Log warning for each element that is not directory.
 */
private List<Path> checkDirectories(List<Path> pathList) {
    List<Path> result = new ArrayList<>();
    for (Path path : pathList) {
        if (!Files.exists(path)) {
            LOGGER.debug("'{}' does not exist", path);
        } else if (!Files.isDirectory(path)) {
            LOGGER.warn("'{}' is not directory", path);
        }
        // todo: should we use not existing paths? this behavior is copied from 'protoc' - it just shows warning
        result.add(path);
    }
    return result;
}
 
Example 12
Source File: ResourceLocator.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 改变目录  Change Directory
 * <p>
 * 路径最后如果是目录也不加 "/"
 *
 * @param path    路径位置
 * @param workDir 已有工作目录
 * @return this
 * @throws ErrorPathException 路径不存在
 */
public ResourceLocator cd(LinkedList<String> workDir, String path) {
    if (path == null || path.equals("")) {
        return this;
    }
    path = path.trim();
    if (path.equals("/")) {
        workDir.clear();
        workDir.add("/");
        return this;
    }
    // 转换路径为绝对路径
    String absPath = toAbsolutePath(path);
    String ofwTmp = ofdDir.getSysAbsPath();
    Path sysPath = Paths.get(ofwTmp + absPath);
    if (Files.exists(sysPath) && Files.isDirectory(sysPath)) {
        // 刷新工作区到指定区域
        workDir.clear();
        workDir.add("/");
        for (String item : absPath.split("/")) {
            item = item.trim();
            if (item.isEmpty()) {
                continue;
            }
            workDir.add(item);
        }
    } else {
        // 如果路径不存在,那么报错
        throw new ErrorPathException("无法切换路径到" + path + ",目录不存在。");
    }
    return this;
}
 
Example 13
Source File: Locations.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void addDirectory(Path dir, boolean warn) {
    if (!Files.isDirectory(dir)) {
        if (warn) {
            log.warning(Lint.LintCategory.PATH,
                    "dir.path.element.not.found", dir);
        }
        return;
    }

    try (Stream<Path> s = Files.list(dir)) {
        s.filter(Locations.this::isArchive)
                .forEach(dirEntry -> addFile(dirEntry, warn));
    } catch (IOException ignore) {
    }
}
 
Example 14
Source File: TRECVidMSRSegmenter.java    From cineast with MIT License 5 votes vote down vote up
/**
 * Constructor for {@link TRECVidMSRSegmenter}.
 *
 * @param path Path to the folder relative to which MSR files will be resolved (based on the name of the input video file).
 */
public TRECVidMSRSegmenter(Path path) {
    this.msrFolderPath = path;
    if (!Files.isDirectory(path)) {
        throw new IllegalArgumentException("The MSR path must point to a directory.");
    }
}
 
Example 15
Source File: GitRepository.java    From copybara with Apache License 2.0 5 votes vote down vote up
@CheckReturnValue
static String validateUrl(String url) throws RepoException, ValidationException {
  RepositoryUtil.validateNotHttp(url);
  if (FULL_URI.matcher(url).matches()) {
    return url;
  }

  // Support local folders
  if (Files.isDirectory(Paths.get(url))) {
    return url;
  }
  throw new RepoException(String.format("URL '%s' is not valid", url));
}
 
Example 16
Source File: PathResolverService.java    From AsciidocFX with Apache License 2.0 5 votes vote down vote up
public boolean isViewable(Path path) {
    return true || Files.isDirectory(path)
            || isAsciidoc(path)
            || isImage(path)
            || isPDF(path)
            || isEpub(path)
            || isMobi(path)
            || isHTML(path)
            || isXML(path)
            || isMarkdown(path);
}
 
Example 17
Source File: PathDocFileFactory.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/** Return true is file identifies a directory. */
public boolean isDirectory() {
    return Files.isDirectory(file);
}
 
Example 18
Source File: AppModelGradleResolver.java    From quarkus with Apache License 2.0 4 votes vote down vote up
private void collectExtensionDeps(Set<ResolvedDependency> resolvedDeps,
        Map<AppArtifactKey, AppDependency> versionMap,
        AppModel.Builder appBuilder,
        List<Dependency> firstLevelExtensions,
        boolean firstLevelExt,
        Set<AppArtifactKey> visited) {
    for (ResolvedDependency dep : resolvedDeps) {
        final AppArtifactKey key = new AppArtifactKey(dep.getModuleGroup(), dep.getModuleName());
        if (!visited.add(key)) {
            continue;
        }
        final AppDependency appDep = versionMap.get(key);
        if (appDep == null) {
            // not a jar
            continue;
        }

        Dependency extDep = null;
        for (Path artifactPath : appDep.getArtifact().getPaths()) {
            if (!Files.exists(artifactPath)) {
                continue;
            }
            if (Files.isDirectory(artifactPath)) {
                extDep = processQuarkusDir(appDep.getArtifact(), artifactPath.resolve(BootstrapConstants.META_INF),
                        appBuilder);
            } else {
                try (FileSystem artifactFs = FileSystems.newFileSystem(artifactPath, null)) {
                    extDep = processQuarkusDir(appDep.getArtifact(), artifactFs.getPath(BootstrapConstants.META_INF),
                            appBuilder);
                } catch (IOException e) {
                    throw new GradleException("Failed to process " + artifactPath, e);
                }
            }
            if (extDep != null) {
                break;
            }
        }

        boolean addChildExtensions = firstLevelExt;
        if (extDep != null && firstLevelExt) {
            firstLevelExtensions.add(extDep);
            addChildExtensions = false;
        }
        final Set<ResolvedDependency> resolvedChildren = dep.getChildren();
        if (!resolvedChildren.isEmpty()) {
            collectExtensionDeps(resolvedChildren, versionMap, appBuilder, firstLevelExtensions, addChildExtensions,
                    visited);
        }
    }
}
 
Example 19
Source File: FileSystem.java    From container with Apache License 2.0 4 votes vote down vote up
public static void zip(Path targetFile, Path... inputFiles) throws IOException {
    if (inputFiles.length == 0) {
        return;
    }
    // recurse into a single base-directory
    if (inputFiles.length == 1 && Files.isDirectory(inputFiles[0])) {
        final Path[] inputs;
        try (Stream<Path> search = Files.find(inputFiles[0], Integer.MAX_VALUE, (p, a) -> true)) {
            inputs = search.toArray(Path[]::new);
        } catch (IOException inner) {
            throw inner;
        }
        zip(targetFile, inputs);
        return;
    }
    // the root to relativize paths against for the name-resolution of the Zip entries
    final Path root = Files.isDirectory(inputFiles[0]) ? inputFiles[0] : inputFiles[0].getParent();
    // ensure parent directory exists
    Files.createDirectories(targetFile.getParent());

    try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetFile,
        StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING))) {
        for (Path externalFile : inputFiles) {
            // skip root
            if (externalFile.equals(root)
                // skip the target file if it's within the resolved input files
                || externalFile.endsWith(targetFile) || targetFile.endsWith(externalFile)) {
                continue;
            }
            // only copy the content of regular files
            if (!Files.isRegularFile(externalFile)) {
                continue;
            }
            final Path relative = root.relativize(externalFile);
            ZipEntry entry = new ZipEntry(relative.toString());
            zos.putNextEntry(entry);
            Files.copy(externalFile, zos);
            zos.closeEntry();
        }
        zos.finish();
    }
}
 
Example 20
Source File: VirtualFileSystemView.java    From snap-desktop with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Checks whether the given path represents a File System
 *
 * @param path the path
 * @return {@code True} if the given file path represents a File System
 */
private boolean isFileSystem(Path path) {
    return !(Files.isSymbolicLink(path) && Files.isDirectory(path));
}