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

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

@Test
public void testCreateSymlinks() throws IOException, URISyntaxException {
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();

    Path newDir = rootPath.resolve("newDir");
    Assert.assertFalse(Files.isSymbolicLink(newDir));

    Path innerDir = newDir.resolve("innerDir");
    Assert.assertFalse(Files.isSymbolicLink(innerDir));

    Path newSymlink = rootPath.resolve("newSymlink");
    Assert.assertTrue(Files.isSymbolicLink(newSymlink));

    Path innerSymlink = newSymlink.resolve("innerSymlink");
    Assert.assertTrue(Files.isSymbolicLink(innerSymlink));

    Path f = innerSymlink.getRoot();
    for (int i=0; i<innerSymlink.getNameCount(); i++) {
        f = f.resolve(innerSymlink.getName(i).toString());
        System.out.println(f + " " + Files.isSymbolicLink(f));
    }
    f = f.resolve(".");
    System.out.println(f + " " + Files.isSymbolicLink(f));
}
 
private File getRelativeSolrHomePath(File solrHome) {
  final Path solrHomePath = solrHome.toPath();
  final Path curDirPath = new File("").getAbsoluteFile().toPath();
  
  if (!solrHomePath.getRoot().equals(curDirPath.getRoot())) {
    // root of current directory and solrHome are not the same, therefore cannot relativize
    return solrHome;
  }
  
  final Path root = solrHomePath.getRoot();
  
  // relativize current directory to root: /tmp/foo -> /tmp/foo/../..
  final File relativizedCurDir = new File(curDirPath.toFile(), curDirPath.relativize(root).toString());
  
  // exclude the root from solrHome: /tmp/foo/solrHome -> tmp/foo/solrHome
  final Path solrHomeRelativeToRoot = root.relativize(solrHomePath);
  
  // create the relative solrHome: /tmp/foo/../../tmp/foo/solrHome
  return new File(relativizedCurDir, solrHomeRelativeToRoot.toString()).getAbsoluteFile();
}
 
源代码3 项目: yajsync   文件: PathOps.java
public static Path subtractPathOrNull(Path parent, Path sub)
{
    if (!parent.endsWith(sub)) {
        throw new IllegalArgumentException(String.format(
                "%s is not a parent path of %s", parent, sub));
    }
    if (parent.getNameCount() == sub.getNameCount()) {
        return parent.getRoot(); // NOTE: return null if parent has no root
    }
    Path res = parent.subpath(0,
                              parent.getNameCount() - sub.getNameCount());
    if (parent.isAbsolute()) {
        return parent.getRoot().resolve(res);
    } else {
        return res;
    }
}
 
@Test
public void testBuildFromDockerFileMerged() {
    imageConfiguration = new ImageConfiguration.Builder()
            .name("myimage")
            .externalConfig(externalConfigMode(PropertyMode.Override))
            .buildConfig(new BuildImageConfiguration.Builder()
                    .dockerFile("/some/path")
                    .cacheFrom((Arrays.asList("foo/bar:latest")))
                    .build()
            )
            .build();

    List<ImageConfiguration> configs = resolveImage(
            imageConfiguration, props()
    );

    assertEquals(1, configs.size());

    BuildImageConfiguration buildConfiguration = configs.get(0).getBuildConfiguration();
    assertNotNull(buildConfiguration);
    buildConfiguration.initAndValidate(null);

    Path absolutePath = Paths.get(".").toAbsolutePath();
    String expectedPath = absolutePath.getRoot() + "some" + File.separator + "path";
    assertEquals(expectedPath, buildConfiguration.getDockerFile().getAbsolutePath());
}
 
源代码5 项目: AsciidocFX   文件: ParserService.java
private void applyForEachInPath(List<Path> pathList, Consumer<Path> consumer, Path root) {

        Path workDirRoot = root.getRoot();

        for (Path path : pathList) {

            Path includePath = null;

            if (workDirRoot.equals(path.getRoot())) {
                includePath = root.relativize(path);
            } else {
                includePath = path.toAbsolutePath();
            }

            if (Objects.nonNull(includePath)) {
                consumer.accept(includePath);
            }
        }
    }
 
源代码6 项目: js-dossier   文件: Paths.java
/**
 * Returns the {@link Path} that represents the longest common prefix for the provided {@code
 * paths}. All paths will be resolved and normalized relative to the given {@code root} directory
 * before computing a common prefix.
 *
 * <p>If all of the provided {@code paths} do not designate
 */
static Path getCommonPrefix(Path root, Collection<Path> paths) {
  if (paths.isEmpty()) {
    return root;
  }
  root = root.toAbsolutePath();
  paths = paths.stream().map(normalizeRelativeTo(root)).collect(toList());

  Path prefix = root.getRoot();
  Path shortest = Ordering.from(length()).min(paths);
  for (Path part : shortest) {
    Path possiblePrefix = prefix.resolve(part);
    if (paths.stream().allMatch(startsWith(possiblePrefix))) {
      prefix = possiblePrefix;
    } else {
      break;
    }
  }
  return prefix;
}
 
源代码7 项目: jimfs   文件: JimfsPathTest.java
private void assertResolvedPathEquals(
    String expected, Path path, String firstResolvePath, String... moreResolvePaths) {
  Path resolved = path.resolve(firstResolvePath);
  for (String additionalPath : moreResolvePaths) {
    resolved = resolved.resolve(additionalPath);
  }
  assertPathEquals(expected, resolved);

  Path relative = pathService.parsePath(firstResolvePath, moreResolvePaths);
  resolved = path.resolve(relative);
  assertPathEquals(expected, resolved);

  // assert the invariant that p.relativize(p.resolve(q)).equals(q) when q does not have a root
  // p = path, q = relative, p.resolve(q) = resolved
  if (relative.getRoot() == null) {
    assertEquals(relative, path.relativize(resolved));
  }
}
 
源代码8 项目: jimfs   文件: PathTester.java
private void testEndsWith(Path path) {
  // empty path doesn't start with any path
  if (root != null || !names.isEmpty()) {
    Path other = path;
    while (other != null) {
      assertTrue(path + ".endsWith(" + other + ") should be true", path.endsWith(other));
      assertTrue(
          path + ".endsWith(" + other + ") should be true", path.endsWith(other.toString()));
      if (other.getRoot() != null && other.getNameCount() > 0) {
        other = other.subpath(0, other.getNameCount());
      } else if (other.getNameCount() > 1) {
        other = other.subpath(1, other.getNameCount());
      } else {
        other = null;
      }
    }
  }
}
 
源代码9 项目: uyuni   文件: ConfigChannelSaltManager.java
/**
 * Get the file params list for salt
 * @param file file
 * @return List of params map
 */
private List<Map<String, Object>> getFileStateParams(ConfigFile file) {
    Path filePath = Paths.get(file.getConfigFileName().getPath());
    if (filePath.getRoot() != null) {
        filePath = filePath.getRoot().relativize(filePath);
    }

    List<Map<String, Object>> fileParams = new LinkedList<>();
    fileParams.add(singletonMap("name", file.getConfigFileName().getPath()));
    fileParams.add(singletonMap("source", getSaltUriForConfigFile(file)));
    fileParams.add(singletonMap("makedirs", true));
    fileParams.addAll(getModeParams(file.getLatestConfigRevision().getConfigInfo()));
    return fileParams;
}
 
源代码10 项目: uyuni   文件: ConfigChannelSaltManager.java
/**
 * Gets the salt URI for given file.
 *
 * @param file the file
 * @return the salt uri for the file (starting with salt://)
 */
public String getSaltUriForConfigFile(ConfigFile file) {
    Path filePath = Paths.get(file.getConfigFileName().getPath());
    if (filePath.getRoot() != null) {
        filePath = filePath.getRoot().relativize(filePath);
    }
    return SALT_FS_PREFIX + getChannelRelativePath(file.getConfigChannel())
            .resolve(filePath);
}
 
protected static String calculateDefaultOutputDirectory(Path currentPath) {
    Path currentAbsolutePath = currentPath.toAbsolutePath();
    Path parent = currentAbsolutePath.getParent();
    if (parent == currentAbsolutePath.getRoot()) {
        return parent.toString();
    } else {
        Path currentNormalizedPath = currentAbsolutePath.normalize();
        return "../" + currentNormalizedPath.getFileName().toString();
    }
}
 
源代码12 项目: Bytecoder   文件: Resources.java
/**
 * Map a resource name to a "safe" file path. Returns {@code null} if
 * the resource name cannot be converted into a "safe" file path.
 *
 * Resource names with empty elements, or elements that are "." or ".."
 * are rejected, as are resource names that translates to a file path
 * with a root component.
 */
private static Path toSafeFilePath(FileSystem fs, String name) {
    // scan elements of resource name
    int next;
    int off = 0;
    while ((next = name.indexOf('/', off)) != -1) {
        int len = next - off;
        if (!mayTranslate(name, off, len)) {
            return null;
        }
        off = next + 1;
    }
    int rem = name.length() - off;
    if (!mayTranslate(name, off, rem)) {
        return null;
    }

    // convert to file path
    Path path;
    if (File.separatorChar == '/') {
        path = fs.getPath(name);
    } else {
        // not allowed to embed file separators
        if (name.contains(File.separator))
            return null;
        path = fs.getPath(name.replace('/', File.separatorChar));
    }

    // file path not allowed to have root component
    return (path.getRoot() == null) ? path : null;
}
 
源代码13 项目: openjdk-jdk9   文件: Resources.java
/**
 * Map a resource name to a "safe" file path. Returns {@code null} if
 * the resource name cannot be converted into a "safe" file path.
 *
 * Resource names with empty elements, or elements that are "." or ".."
 * are rejected, as are resource names that translates to a file path
 * with a root component.
 */
private static Path toSafeFilePath(FileSystem fs, String name) {
    // scan elements of resource name
    int next;
    int off = 0;
    while ((next = name.indexOf('/', off)) != -1) {
        int len = next - off;
        if (!mayTranslate(name, off, len)) {
            return null;
        }
        off = next + 1;
    }
    int rem = name.length() - off;
    if (!mayTranslate(name, off, rem)) {
        return null;
    }

    // convert to file path
    Path path;
    if (File.separatorChar == '/') {
        path = fs.getPath(name);
    } else {
        // not allowed to embed file separators
        if (name.contains(File.separator))
            return null;
        path = fs.getPath(name.replace('/', File.separatorChar));
    }

    // file path not allowed to have root component
    return (path.getRoot() == null) ? path : null;
}
 
源代码14 项目: ignite   文件: IgniteKernal.java
/**
 * @param clsPathEntry Classpath string to process.
 * @param clsPathContent StringBuilder to attach path to.
 */
private void ackClassPathWildCard(String clsPathEntry, SB clsPathContent) {
    final int lastSeparatorIdx = clsPathEntry.lastIndexOf(File.separator);

    final int asteriskIdx = clsPathEntry.indexOf('*');

    //just to log possibly incorrent entries to err
    if (asteriskIdx >= 0 && asteriskIdx < lastSeparatorIdx)
        throw new RuntimeException("Could not parse classpath entry");

    final int fileMaskFirstIdx = lastSeparatorIdx + 1;

    final String fileMask =
        (fileMaskFirstIdx >= clsPathEntry.length()) ? "*.jar" : clsPathEntry.substring(fileMaskFirstIdx);

    Path path = Paths.get(lastSeparatorIdx > 0 ? clsPathEntry.substring(0, lastSeparatorIdx) : ".")
        .toAbsolutePath()
        .normalize();

    if (lastSeparatorIdx == 0)
        path = path.getRoot();

    try {
        DirectoryStream<Path> files =
            Files.newDirectoryStream(path, fileMask);

        for (Path f : files) {
            String s = f.toString();

            if (s.toLowerCase().endsWith(".jar"))
                clsPathContent.a(f.toString()).a(";");
        }
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}