java.nio.file.Path#subpath ( )源码实例Demo

下面列出了java.nio.file.Path#subpath ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: size-analyzer   文件: ZipFileData.java
@Override
public Path getPathWithinModule() {
  if (cachedPathWithinModule != null) {
    return cachedPathWithinModule;
  }

  Path fullPath = getPathWithinRoot();
  if (fullPath.getNameCount() <= 1
      || fullPath.startsWith("BUNDLE-METADATA")
      || fullPath.startsWith("META-INF")) {
    cachedPathWithinModule = fullPath;
  } else {
    cachedPathWithinModule = fullPath.subpath(1, fullPath.getNameCount());
  }
  return cachedPathWithinModule;
}
 
源代码2 项目: n4js   文件: N4JSProjectExplorerHelper.java
private String getRootLocationName(final IN4JSProject project) {
	String rootLocationName = null;
	List<IN4JSProject> shadowingProjects = shadowingInfoHelper.findShadowingProjects(project);
	if (!shadowingProjects.isEmpty()) {
		IN4JSProject shadowedProject = shadowingProjects.get(0);
		if (shadowedProject.isExternal()) {
			FileURI location = (FileURI) shadowedProject.getLocation();
			FileURI rootLocation = externalLibraryWorkspace.getRootLocationForResource(location);
			if (rootLocation != null) {
				Path rootPath = rootLocation.toFileSystemPath();
				Path subpath = rootPath.subpath(rootPath.getNameCount() - 2, rootPath.getNameCount());
				rootLocationName = subpath.toString();
			} else {
				rootLocationName = "unknown";
			}
		} else {
			rootLocationName = "workspace";
		}
		rootLocationName = " [shadowed by " + rootLocationName + "]";
	}
	return rootLocationName;
}
 
源代码3 项目: jmonkeybuilder   文件: AbstractFileEditor.java
/**
 * Notify about changed the edited file.
 *
 * @param prevFile the prev file.
 * @param newFile  the new file.
 */
@FxThread
private void notifyChangedEditedFile(final @NotNull Path prevFile, final @NotNull Path newFile) {

    final Path editFile = getEditFile();

    if (editFile.equals(prevFile)) {
        setEditFile(newFile);
        return;
    }

    if (!editFile.startsWith(prevFile)) return;

    final Path relativeFile = editFile.subpath(prevFile.getNameCount(), editFile.getNameCount());
    final Path resultFile = newFile.resolve(relativeFile);

    setEditFile(resultFile);
}
 
源代码4 项目: buck   文件: DefaultDefectReporter.java
private void addFilesToArchive(CustomZipOutputStream out, ImmutableSet<Path> paths)
    throws IOException {
  for (Path logFile : paths) {
    Path destPath = logFile;
    if (destPath.isAbsolute()) {
      // If it's an absolute path, make it relative instead
      destPath = destPath.subpath(0, logFile.getNameCount());
      Preconditions.checkArgument(!destPath.isAbsolute(), "Should be a relative path", destPath);
    }
    if (destPath.getFileName().toString().startsWith(".")) {
      // If the file is hidden(UNIX terms) save it as normal file.
      destPath =
          Optional.ofNullable(destPath.getParent())
              .orElse(Paths.get(""))
              .resolve(destPath.getFileName().toString().replaceAll("^\\.*", ""));
    }

    out.putNextEntry(new CustomZipEntry(destPath));

    try (InputStream input = filesystem.newFileInputStream(logFile)) {
      ByteStreams.copy(input, out);
    }
    out.closeEntry();
  }
}
 
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
		throws IOException {
	if (file.getNameCount() > 3 && file.toString().endsWith(".class")) {
		int fnc = file.getNameCount();
		if (fnc > 3) { // There is a package name - e.g.
			// /modules/java.base/java/lang/Object.class
			Path packagePath = file.subpath(2, fnc - 1); // e.g. java/lang
			String packagePathString = packagePath.toString() + "/";
			CompilationInfoCache.this.packageCache.put(packagePathString,
					file.subpath(0, fnc - 1)); // java/lang
			// ->
			// /modules/java.base/java/lang
		}
	}
	return FileVisitResult.CONTINUE;
}
 
源代码6 项目: PeerWasp   文件: TestFolderComposite.java
/**
 * Appends a new component to the FolderComposite. Inexistent folders are added on the
 * fly. Existing items are replaced. Triggers updates of content and name hashes.
 */
@Override
public synchronized void putComponent(Path remainingPath, FileComponent component) {
	remainingPath = stripOffPrefix(remainingPath, getPath());

	Path nextLevelPath = remainingPath.getName(0);

	// if we are at the last recursion, perform the add, else recursively continue
	if (remainingPath.getNameCount() == 1) {
		addComponentToChildren(nextLevelPath, component);
	} else {
		FileComponent nextLevel = getChildren().get(nextLevelPath);
		if (nextLevel == null) {
			// next level does not exist yet, create it
			Path childPath = constructFullPath(nextLevelPath);
			nextLevel = new TestFolderComposite(childPath, updateContentHash);
			addComponentToChildren(nextLevelPath, nextLevel);
		}
		Path newRemainingPath = remainingPath.subpath(1, remainingPath.getNameCount());
		((FolderComposite)nextLevel).putComponent(newRemainingPath, component);
	}
}
 
源代码7 项目: yajsync   文件: RestrictedPath.java
/**
 * resolve other in a secure manner without any call to stat.
 * @throws RsyncSecurityException
 */
private Path resolve(Path path) throws RsyncSecurityException
{
    Path result;
    Path normalized = path.normalize();
    if (normalized.startsWith(_moduleName)) {
        if (normalized.getNameCount() == 1) {
            result = _rootPath;
        } else {
            Path strippedOfModulePrefix =
                    normalized.subpath(1, normalized.getNameCount());
            result = _rootPath.resolve(strippedOfModulePrefix).normalize();
        }
    } else {
        throw new RsyncSecurityException(String.format(
            "\"%s\" is outside virtual dir for module %s",
            path, _moduleName));
    }
    if (path.endsWith(_dotDir)) {
        return result.resolve(_dotDir);
    } else {
        return result;
    }
}
 
源代码8 项目: buck   文件: MerkleTreeNodeCache.java
private TreeNodeBuilder getMutableDirectory(Path dir) {
  Preconditions.checkArgument(dir.getNameCount() > getPathSegments());
  Path subPath = dir.subpath(0, getPathSegments() + 1);
  verifyPathNotYetProcessed(subPath);
  return childrenBuilder
      .compute(
          subPath,
          (ignored, value) ->
              Either.ofRight(
                  value == null
                      ? new TreeNodeBuilder(subPath)
                      : value.transform(TreeNodeBuilder::new, right -> right)))
      .getRight();
}
 
源代码9 项目: buck   文件: SymlinkCache.java
private Map<Path, Path> inputFilesUnderSymlink(
    // We use Collection<Path> instead of Iterable<Path> to prevent
    // accidentally passing in Path, since Path itself is Iterable<Path>.
    Collection<ForwardRelativePath> inputs, ProjectFilesystem projectFilesystem)
    throws IOException {
  Map<Path, Path> newSymlinksEncountered = new HashMap<>();
  for (ForwardRelativePath input : inputs) {
    Path inputPath = input.toPath(projectFilesystem.getFileSystem());
    for (int i = 1; i < inputPath.getNameCount(); i++) {
      Path subpath = inputPath.subpath(0, i);
      Optional<Path> resolvedSymlink = symlinkExistenceCache.get(subpath);
      if (resolvedSymlink != null) {
        if (resolvedSymlink.isPresent()) {
          LOG.verbose("Detected cached symlink %s -> %s", subpath, resolvedSymlink.get());
          newSymlinksEncountered.put(subpath, resolvedSymlink.get());
        }
        // If absent, not a symlink.
      } else {
        // Not cached, look it up.
        if (projectFilesystem.isSymLink(subpath)) {
          Path symlinkTarget = projectFilesystem.resolve(subpath).toRealPath();
          Path relativeSymlinkTarget =
              projectFilesystem.getPathRelativeToProjectRoot(symlinkTarget).orElse(symlinkTarget);
          LOG.verbose("Detected symbolic link %s -> %s", subpath, relativeSymlinkTarget);
          newSymlinksEncountered.put(subpath, relativeSymlinkTarget);
          symlinkExistenceCache.put(subpath, Optional.of(relativeSymlinkTarget));
        } else {
          symlinkExistenceCache.put(subpath, Optional.empty());
        }
      }
    }
  }
  return newSymlinksEncountered;
}
 
源代码10 项目: nifi   文件: MergeContent.java
private String getPath(final FlowFile flowFile) {
    Path path = Paths.get(flowFile.getAttribute(CoreAttributes.PATH.key()));
    if (path.getNameCount() == 0) {
        return "";
    }

    if (".".equals(path.getName(0).toString())) {
        path = path.getNameCount() == 1 ? null : path.subpath(1, path.getNameCount());
    }

    return path == null ? "" : path.toString() + "/";
}
 
源代码11 项目: spring-init   文件: MemoryBasedJavaFileManager.java
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
	if (file.getNameCount() > 2 && file.toString().endsWith(".class")) {
		// /modules/jdk.rmic/sun/tools/tree/CaseStatement.class
		String moduleName = file.getName(1).toString(); // jdk.rmic
		Path moduleRootPath = file.subpath(0, 2); // /modules/jdk.rmic
		if (!modules.containsKey(moduleName)) {
			modules.put(moduleName, moduleRootPath);
		}
	}
	return FileVisitResult.CONTINUE;
}
 
源代码12 项目: openjdk-jdk9   文件: JImageExtractTest.java
public void testExtractFromDir() {
    Path imagePath = Paths.get(getImagePath());
    Path imageDirPath = imagePath.subpath(0, imagePath.getNameCount() - 1);
    jimage("extract", imageDirPath.toString())
            .assertFailure()
            .assertShowsError();
}
 
源代码13 项目: mycore   文件: MCRAutoDeploy.java
private void deployWebResources(final ServletContext servletContext, final MCRComponent comp) {
    final Path webRoot = Optional.ofNullable(servletContext.getRealPath("/")).map(Paths::get).orElse(null);
    if (webRoot != null) {
        int resourceDirPathComponents = RESOURCE_DIR.split("/").length;
        try (InputStream fin = Files.newInputStream(comp.getJarFile().toPath());
            ZipInputStream zin = new ZipInputStream(fin)) {
            LOGGER.info("Deploy web resources from {} to {}...", comp.getName(), webRoot);
            for (ZipEntry zipEntry = zin.getNextEntry(); zipEntry != null; zipEntry = zin.getNextEntry()) {
                if (zipEntry.getName().startsWith(RESOURCE_DIR)) {
                    Path relativePath = toNativePath(zipEntry);
                    if (relativePath.getNameCount() > resourceDirPathComponents) {
                        //strip RESOURCE_DIR:
                        relativePath = relativePath.subpath(resourceDirPathComponents, relativePath.getNameCount());
                        Path target = webRoot.resolve(relativePath);
                        if (zipEntry.isDirectory()) {
                            Files.createDirectories(target);
                        } else if (isUnzipRequired(zipEntry, target)) {
                            LOGGER.debug("...deploy {}", zipEntry.getName());
                            Files.copy(zin, target, StandardCopyOption.REPLACE_EXISTING);
                            Files.setLastModifiedTime(target, zipEntry.getLastModifiedTime());
                        }
                    }
                }
            }
            LOGGER.info("...done.");
        } catch (final IOException e) {
            LOGGER.error("Could not deploy web resources of " + comp.getJarFile() + "!", e);
        }
    }
}
 
源代码14 项目: bazel   文件: AndroidResourceOutputs.java
/** Collects all the compiled resources into an archive, normalizing the paths to the root. */
public static Path archiveCompiledResources(
    final Path archiveOut,
    final Path databindingResourcesRoot,
    final Path compiledRoot,
    final List<Path> compiledArtifacts)
    throws IOException {
  final Path relativeDatabindingProcessedResources =
      databindingResourcesRoot.getRoot().relativize(databindingResourcesRoot);

  try (ZipBuilder builder = ZipBuilder.createFor(archiveOut)) {
    for (Path artifact : compiledArtifacts) {
      Path relativeName = artifact;

      // remove compiled resources prefix
      if (artifact.startsWith(compiledRoot)) {
        relativeName = compiledRoot.relativize(relativeName);
      }
      // remove databinding prefix
      if (relativeName.startsWith(relativeDatabindingProcessedResources)) {
        relativeName =
            relativeName.subpath(
                relativeDatabindingProcessedResources.getNameCount(),
                relativeName.getNameCount());
      }

      builder.addEntry(
          relativeName.toString(),
          Files.readAllBytes(artifact),
          ZipEntry.STORED,
          ResourceCompiler.getCompiledType(relativeName.toString()).asComment());
    }
  }
  return archiveOut;
}
 
源代码15 项目: meghanada-server   文件: ModuleHelper.java
public static Optional<String> pathToModule(Path p) {

    if (p.startsWith(File.separator + "modules" + File.separator)) {
      // module path
      Path subpath = p.subpath(1, 2);
      return Optional.of(subpath.toString());
    }
    return Optional.empty();
  }
 
源代码16 项目: buck   文件: PathArguments.java
/**
 * Filter files under the project root, and convert to canonical relative path style. For example,
 * the project root is /project, 1. file path /project/./src/com/facebook/./test/../Test.java will
 * be converted to src/com/facebook/Test.java 2. file path
 * /otherproject/src/com/facebook/Test.java will be ignored.
 */
static ReferencedFiles getCanonicalFilesUnderProjectRoot(
    AbsPath projectRoot, Iterable<String> nonCanonicalFilePaths) throws IOException {
  // toRealPath() is used throughout to resolve symlinks or else the Path.startsWith() check will
  // not be reliable.
  ImmutableSet.Builder<RelPath> projectFiles = ImmutableSet.builder();
  ImmutableSet.Builder<AbsPath> nonProjectFiles = ImmutableSet.builder();
  AbsPath normalizedRoot = projectRoot.toRealPath();
  for (String filePath : nonCanonicalFilePaths) {
    Path canonicalFullPath = Paths.get(filePath);
    if (!canonicalFullPath.isAbsolute()) {
      canonicalFullPath = projectRoot.resolve(canonicalFullPath).getPath();
    }
    if (!canonicalFullPath.toFile().exists()) {
      nonProjectFiles.add(AbsPath.of(canonicalFullPath));
      continue;
    }
    canonicalFullPath = canonicalFullPath.toRealPath();

    // Ignore files that aren't under project root.
    if (canonicalFullPath.startsWith(normalizedRoot.getPath())) {
      Path relativePath =
          canonicalFullPath.subpath(
              normalizedRoot.getPath().getNameCount(), canonicalFullPath.getNameCount());
      projectFiles.add(RelPath.of(relativePath));
    } else {
      nonProjectFiles.add(AbsPath.of(canonicalFullPath));
    }
  }
  return new ReferencedFiles(projectFiles.build(), nonProjectFiles.build());
}
 
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
		throws IOException {
	if (file.getNameCount() > 2 && file.toString().endsWith(".class")) {
		// /modules/jdk.rmic/sun/tools/tree/CaseStatement.class
		String moduleName = file.getName(1).toString(); // jdk.rmic
		Path moduleRootPath = file.subpath(0, 2); // /modules/jdk.rmic
		if (!this.modules.containsKey(moduleName)) {
			this.modules.put(moduleName, moduleRootPath);
		}
	}
	return FileVisitResult.CONTINUE;
}
 
源代码18 项目: AsciidocFX   文件: DirectoryService.java
public String interPath(Path path) {

        try {
            Path subpath = path.subpath(0, path.getNameCount());
            return subpath.toString().replace('\\', '/');
        } catch (Exception e) {
            return ".";
        }
    }
 
源代码19 项目: PeerWasp   文件: FolderComposite.java
/**
 * Deletes the FileComponent at location remainingPath. Triggers updates of
 * content and name hashes.
 *
 * @return The deleted component. If it does not exist, null is returned
 */
public synchronized FileComponent deleteComponent(Path remainingPath) {
	remainingPath = stripOffPrefix(remainingPath, getPath());

	Path nextLevelPath = remainingPath.getName(0);

	FileComponent removed = null;
	if (remainingPath.getNameCount() == 1) {

		children.get(nextLevelPath);
		FileComponent toRemove = children.get(nextLevelPath);
		if(toRemove != null){
			if(toRemove instanceof FolderComposite){
				removeBottomUp((FolderComposite)toRemove);
			}
			removed = children.remove(nextLevelPath);
		}
		if (updateContentHash) {
			updateContentHash();
		}
		updateStructureHash();
	} else {
		FileComponent nextLevel = children.get(nextLevelPath);
		if (nextLevel != null && nextLevel.isFolder()) {
			Path newRemainingPath = remainingPath.subpath(1, remainingPath.getNameCount());
			removed = ((FolderComposite)nextLevel).deleteComponent(newRemainingPath);
		}
	}
	return removed;
}
 
源代码20 项目: buck   文件: BuckUnixPathTest.java
@Test(expected = IllegalArgumentException.class)
@Parameters({",0,1", "a,-1,1", "/a,-1,1", "a,0,2", "/a,0,2", "a/b,1,0", "/a/b/c/d,0,5"})
public void subpathMethodException(String data, int beginIndex, int endIndex) {
  Path path = BuckUnixPathUtils.createPath(data);
  path.subpath(beginIndex, endIndex);
}