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

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

源代码1 项目: openjdk-jdk9   文件: RegistryImpl.java
/**
 * Convert class path specification into an array of file URLs.
 *
 * The path of the file is converted to a URI then into URL
 * form so that reserved characters can safely appear in the path.
 */
private static URL[] pathToURLs(String path) {
    List<URL> paths = new ArrayList<>();
    for (String entry: path.split(File.pathSeparator)) {
        Path p = Paths.get(entry);
        try {
            p = p.toRealPath();
        } catch (IOException x) {
            p = p.toAbsolutePath();
        }
        try {
            paths.add(p.toUri().toURL());
        } catch (MalformedURLException e) {
            //ignore / skip entry
        }
    }
    return paths.toArray(new URL[0]);
}
 
源代码2 项目: raft-java   文件: Snapshot.java
/**
 * 打开snapshot data目录下的文件,
 * 如果是软链接,需要打开实际文件句柄
 * @return 文件名以及文件句柄map
 */
public TreeMap<String, SnapshotDataFile> openSnapshotDataFiles() {
    TreeMap<String, SnapshotDataFile> snapshotDataFileMap = new TreeMap<>();
    String snapshotDataDir = snapshotDir + File.separator + "data";
    try {
        Path snapshotDataPath = FileSystems.getDefault().getPath(snapshotDataDir);
        snapshotDataPath = snapshotDataPath.toRealPath();
        snapshotDataDir = snapshotDataPath.toString();
        List<String> fileNames = RaftFileUtils.getSortedFilesInDirectory(snapshotDataDir, snapshotDataDir);
        for (String fileName : fileNames) {
            RandomAccessFile randomAccessFile = RaftFileUtils.openFile(snapshotDataDir, fileName, "r");
            SnapshotDataFile snapshotFile = new SnapshotDataFile();
            snapshotFile.fileName = fileName;
            snapshotFile.randomAccessFile = randomAccessFile;
            snapshotDataFileMap.put(fileName, snapshotFile);
        }
    } catch (IOException ex) {
        LOG.warn("readSnapshotDataFiles exception:", ex);
        throw new RuntimeException(ex);
    }
    return snapshotDataFileMap;
}
 
源代码3 项目: appengine-plugins-core   文件: PathResolver.java
@VisibleForTesting
static void getLocationsFromLink(List<String> possiblePaths, Path link) {
  try {
    Path resolvedLink = link.toRealPath();
    Path possibleBinDir = resolvedLink.getParent();
    // check if the parent is "bin", we actually depend on that for other resolution
    if (possibleBinDir != null && possibleBinDir.getFileName().toString().equals("bin")) {
      Path possibleCloudSdkHome = possibleBinDir.getParent();
      if (possibleCloudSdkHome != null && Files.exists(possibleCloudSdkHome)) {
        possiblePaths.add(possibleCloudSdkHome.toString());
      }
    }
  } catch (IOException ioe) {
    // intentionally ignore exception
    logger.log(Level.FINE, "Non-critical exception when searching for cloud-sdk", ioe);
  }
}
 
源代码4 项目: lucene-solr   文件: IOUtils.java
/** Rough Linux-only heuristics to determine whether the provided
 *  {@code Path} is backed by spinning storage.  For example, this
 *  returns false if the disk is a solid-state disk.
 *
 *  @param path a location to check which must exist. the mount point will be determined from this location.
 *  @return false if the storage is non-rotational (e.g. an SSD), or true if it is spinning or could not be determined
 *  @throws IOException if {@code path} does not exist.
 *
 *  @lucene.internal */
public static boolean spins(Path path) throws IOException {
  // resolve symlinks (this will throw exception if the path does not exist)
  path = path.toRealPath();
  
  // Super cowboy approach, but seems to work!
  if (!Constants.LINUX) {
    return true; // no detection
  }

  try {
    return spinsLinux(path);
  } catch (Exception exc) {
    // our crazy heuristics can easily trigger SecurityException, AIOOBE, etc ...
    return true;
  }
}
 
源代码5 项目: synopsys-detect   文件: DirectoryOptions.java
@Nullable
private Path toRealPath(@Nullable Path rawPath) throws IOException {
    if (rawPath == null) {
        return null;
    }
    return rawPath.toRealPath();
}
 
源代码6 项目: vscode-as3mxml   文件: GenericSDKUtils.java
/**
 * Attempts to find a valid SDK by searching for the FLEX_HOME
 * environment variable and testing the PATH environment variable.
 */
public static String findSDK()
{
	String flexHome = System.getenv(ENV_FLEX_HOME);
	if(flexHome != null && isValidSDK(Paths.get(flexHome)))
	{
		return flexHome;
	}
	String envPath = System.getenv(ENV_PATH);
	if(envPath != null)
	{
		String[] paths = envPath.split(File.pathSeparator);
		for(String currentPath : paths)
		{
			File file = new File(currentPath, MXMLC);
			if(file.exists() && !file.isDirectory())
			{
				//this may a symbolic link rather than the actual file,
				//such as when Apache Royale is installed with NPM on
				//Mac, so get the real path.
				Path sdkPath = file.toPath();
				try
				{
					sdkPath = sdkPath.toRealPath();
				}
				catch(IOException e)
				{
					//didn't seem to work, for some reason
					return null;
				}
				sdkPath = sdkPath.getParent().getParent().getParent();
				if(isValidSDK(sdkPath))
				{
					return sdkPath.toString();
				}
			}
		}
	}
	return null;
}
 
源代码7 项目: TencentKona-8   文件: WriteableUserPath.java
public WriteableUserPath(Path path) throws IOException {
    controlContext = AccessController.getContext();
    // verify that the path is writeable
    if (Files.exists(path) && !Files.isWritable(path)) {
        // throw same type of exception as FileOutputStream
        // constructor, if file can't be opened.
        throw new FileNotFoundException("Could not write to file: " + path.toAbsolutePath());
    }
    // will throw if non-writeable
    BufferedWriter fw = Files.newBufferedWriter(path);
    fw.close();
    this.original = path;
    this.real = path.toRealPath();
    this.text = real.toString();
}
 
源代码8 项目: helidon-build-tools   文件: MavenCommand.java
/**
 * Finds the {@code mvn} executable. Searches using the following, in order:
 * <ol>
 *     <li>The {@code MAVEN_HOME} environment variable</li>
 *     <li>The {@code MVN_HOME} environment variable</li>
 *     <li>The {@code PATH} environment variable</li>
 * </ol>
 *
 * @return The path.
 * @throws IllegalStateException if not found.
 */
public static Path mavenExecutable() {
    if (MAVEN_EXECUTABLE.get() == null) {
        Path maven;
        Optional<Path> path = FileUtils.findExecutableInPath(MAVEN_BINARY_NAME);
        if (path.isPresent()) {
            maven = path.get();
        } else {
            maven = toMavenExecutable(MAVEN_HOME_VAR);
            if (maven == null) {
                maven = toMavenExecutable(MVN_HOME_VAR);
                if (maven == null) {
                    throw new IllegalStateException(MAVEN_BINARY_NAME + " not found. Please add it to "
                                                    + "your PATH or set either the MAVEN_HOME or "
                                                    + "MVN_HOME environment variables.");
                }
            }
        }
        try {
            maven = maven.toRealPath();
            Path shimmed = maven.getParent().getParent().resolve(MAVEN_SHIM_TARGET);
            if (Files.exists(shimmed)) {
                maven = shimmed;
            }
            MAVEN_EXECUTABLE.set(maven.toRealPath());
        } catch (IOException ex) {
            throw new IllegalStateException(ex.getMessage());
        }
    }
    return MAVEN_EXECUTABLE.get();
}
 
@Override
public Optional<AppleDeveloperDirectoryForTestsProvider> createToolchain(
    ToolchainProvider toolchainProvider,
    ToolchainCreationContext context,
    TargetConfiguration toolchainTargetConfiguration) {
  AppleConfig appleConfig = context.getBuckConfig().getView(AppleConfig.class);
  Optional<String> xcodeDeveloperDirectory = appleConfig.getXcodeDeveloperDirectoryForTests();
  Path developerDirectoryForTests;
  if (xcodeDeveloperDirectory.isPresent()) {
    Path developerDirectory =
        context
            .getBuckConfig()
            .resolvePathThatMayBeOutsideTheProjectFilesystem(
                Paths.get(xcodeDeveloperDirectory.get()));
    try {
      developerDirectoryForTests = developerDirectory.toRealPath();
    } catch (IOException e) {
      developerDirectoryForTests = developerDirectory;
    }
  } else {
    developerDirectoryForTests =
        toolchainProvider
            .getByName(
                AppleDeveloperDirectoryProvider.DEFAULT_NAME,
                toolchainTargetConfiguration,
                AppleDeveloperDirectoryProvider.class)
            .getAppleDeveloperDirectory();
  }

  return Optional.of(AppleDeveloperDirectoryForTestsProvider.of(developerDirectoryForTests));
}
 
源代码10 项目: openjdk-jdk8u   文件: WriteableUserPath.java
public WriteableUserPath(Path path) throws IOException {
    controlContext = AccessController.getContext();
    // verify that the path is writeable
    if (Files.exists(path) && !Files.isWritable(path)) {
        // throw same type of exception as FileOutputStream
        // constructor, if file can't be opened.
        throw new FileNotFoundException("Could not write to file: " + path.toAbsolutePath());
    }
    // will throw if non-writeable
    BufferedWriter fw = Files.newBufferedWriter(path);
    fw.close();
    this.original = path;
    this.real = path.toRealPath();
    this.text = real.toString();
}
 
源代码11 项目: baleen   文件: FolderReader.java
private void registerFolders() {
  for (String folder : folders) {
    try {
      Path p = Paths.get(folder);
      p = p.toRealPath();

      if (recursive) {
        Files.walkFileTree(
            p,
            new SimpleFileVisitor<Path>() {
              @Override
              public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr)
                  throws IOException {
                registerDirectory(dir);
                return FileVisitResult.CONTINUE;
              }
            });
      } else {
        registerDirectory(p);
      }
      addFilesFromDir(p.toFile());
    } catch (IOException ioe) {
      getMonitor()
          .warn(
              "Could not find or register folder '{}' or it's subfolders - folder will be skipped",
              folder,
              ioe);
    }
  }
}
 
源代码12 项目: consulo   文件: PathManagerEx.java
@Nonnull
public static Path getAppSystemDir() {
  Path path = Paths.get(ContainerPathManager.get().getSystemPath());
  try {
    return path.toRealPath();
  }
  catch (IOException e) {
    LOGGER.error(e);
  }
  return path;
}
 
源代码13 项目: util   文件: SafeFiles.java
/**
 * Fsync a path and all parents all the way up to the fs root.
 *
 * @param path The path that we want to fsync.
 */
private static void fsyncLineage(final Path path) throws IOException {
    Path cursor = path.toRealPath();
    while (cursor != null) {
        fsync(cursor);
        cursor = cursor.getParent();
    }
}
 
源代码14 项目: qpid-broker-j   文件: KerberosUtilities.java
private Path transformLoginConfig(String hostName) throws IOException
{
    final String resourceName = isIBM() ? LOGIN_IBM_CONFIG_RESOURCE : LOGIN_CONFIG_RESOURCE;
    final URL resource = KerberosUtilities.class.getClassLoader().getResource(resourceName);
    if (resource == null)
    {
        throw new IllegalArgumentException(String.format("Unknown resource '%s'", resourceName));
    }
    final String config;
    try (InputStream is = resource.openStream())
    {
        config = new String(ByteStreams.toByteArray(is), UTF_8);
    }
    catch (IOException e)
    {
        throw new IOException(String.format("Failed to load resource '%s'", resource.toExternalForm()), e);
    }
    final String newConfig = config.replace("AMQP/localhost", "AMQP/" + hostName)
                                   .replace("target/" + BROKER_KEYTAB, toAbsolutePath(BROKER_KEYTAB))
                                   .replace("target/" + CLIENT_KEYTAB, toAbsolutePath(CLIENT_KEYTAB));

    final Path file = Paths.get("target", LOGIN_CONFIG_RESOURCE);
    Files.write(file,
                newConfig.getBytes(UTF_8),
                StandardOpenOption.WRITE,
                StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING);
    return file.toRealPath(LinkOption.NOFOLLOW_LINKS);
}
 
源代码15 项目: 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());
}
 
源代码16 项目: smarthome   文件: SysfsUsbSerialScanner.java
/**
 * In the sysfs, the directory 'class/tty' contains a symbolic link for every serial port style device, i.e., also
 * for serial devices. This symbolic link points to the directory for that device within the sysfs device tree. This
 * method returns the directory to which this symbolic link points for a given serial port.
 * <p/>
 * If the symbolic link cannot be converted to the real path, null is returned and a warning is logged.
 */
private @Nullable Path getSysfsDevicePath(Path ttyFile) {
    try {
        return ttyFile.toRealPath();
    } catch (IOException e) {
        logger.warn("Could not find the device path for {} in the sysfs: {}", ttyFile, e.getMessage());
        return null;
    }
}
 
源代码17 项目: copybara   文件: FileUtil.java
/**
 * Resolves {@code symlink} recursively until it finds a regular file or directory. It also
 * checks that all its intermediate paths jumps are under {@code matcher}.
 */
public static ResolvedSymlink resolveSymlink(PathMatcher matcher, Path symlink)
    throws IOException {
  // Normalize since matcher glob:foo/bar/file* doesn't match foo/bar/../bar/file*
  Path path = symlink.normalize();
  checkArgument(matcher.matches(path), "%s doesn't match %s", path, matcher);

  Set<Path> visited = new LinkedHashSet<>();
  while (Files.isSymbolicLink(path)) {
    visited.add(path);
    // Avoid 'dot' -> . like traps by capping to a sane limit
    if (visited.size() > 50) {
      throw new IOException("Symlink cycle detected:\n  "
          + Joiner.on("\n  ").join(Iterables.concat(visited, ImmutableList.of(symlink))));
    }
    Path newPath = Files.readSymbolicLink(path);
    if (!newPath.isAbsolute()) {
      newPath = path.resolveSibling(newPath).toAbsolutePath().normalize();
    } else {
      newPath = newPath.normalize();
    }
    if (!matcher.matches(newPath)) {
      if (!Files.isDirectory(newPath)
          // Special support for symlinks in the form of ROOT/symlink -> '.'. Technically we
          // shouldn't allow this because of our glob implementation, but this is a regression
          // from the old code and the correct behavior is difficult to understand by our users.
          || !matcher.matches(newPath.resolve("copybara_random_path.txt"))) {
        Path realPath = newPath.toRealPath();
        return new ResolvedSymlink(realPath, /*allUnderRoot=*/ false);
      }
    }
    path = newPath;
  }
  return new ResolvedSymlink(path, /*allUnderRoot=*/ true);
}
 
源代码18 项目: lucene-solr   文件: ReutersContentSource.java
@Override
public DocData getNextDocData(DocData docData) throws NoMoreDataException, IOException {
  Path f = null;
  String name = null;
  synchronized (this) {
    if (nextFile >= inputFiles.size()) {
      // exhausted files, start a new round, unless forever set to false.
      if (!forever) {
        throw new NoMoreDataException();
      }
      nextFile = 0;
      iteration++;
    }
    f = inputFiles.get(nextFile++);
    name = f.toRealPath() + "_" + iteration;
  }

  try (BufferedReader reader = Files.newBufferedReader(f, StandardCharsets.UTF_8)) {
    // First line is the date, 3rd is the title, rest is body
    String dateStr = reader.readLine();
    reader.readLine();// skip an empty line
    String title = reader.readLine();
    reader.readLine();// skip an empty line
    StringBuilder bodyBuf = new StringBuilder(1024);
    String line = null;
    while ((line = reader.readLine()) != null) {
      bodyBuf.append(line).append(' ');
    }
    
    addBytes(Files.size(f));
    
    Date date = parseDate(dateStr.trim());
    
    docData.clear();
    docData.setName(name);
    docData.setBody(bodyBuf.toString());
    docData.setTitle(title);
    docData.setDate(date);
    return docData;
  }
}
 
源代码19 项目: ph-commons   文件: PathFuncTest.java
@Test
public void testTraverse2 () throws IOException
{
  final Path p = Paths.get ("cde/../pom.xml");
  assertFalse (p.isAbsolute ());
  if (WIN)
  {
    assertTrue (Files.exists (p));
  }
  else
  {
    assertFalse (Files.exists (p));
  }
  assertTrue (Files.exists (p.normalize ()));
  assertFalse (Files.isDirectory (p));
  if (!WIN)
    assertFalse (Files.isExecutable (p));
  assertFalse (Files.isHidden (p));
  if (WIN)
  {
    assertTrue (Files.isReadable (p));
    assertTrue (Files.isReadable (p.normalize ()));
    assertTrue (Files.isRegularFile (p));
    assertTrue (Files.isRegularFile (p.normalize ()));
  }
  else
  {
    assertFalse (Files.isReadable (p));
    assertTrue (Files.isReadable (p.normalize ()));
    assertFalse (Files.isRegularFile (p));
    assertTrue (Files.isRegularFile (p.normalize ()));
  }
  assertTrue (Files.isSameFile (p, p));
  assertFalse (Files.isSymbolicLink (p));
  if (WIN)
  {
    assertTrue (Files.isWritable (p));
    assertTrue (Files.isWritable (p.normalize ()));
  }
  else
  {
    assertFalse (Files.isWritable (p));
    assertTrue (Files.isWritable (p.normalize ()));
  }
  assertEquals ("cde" + SEP + ".." + SEP + "pom.xml", p.toString ());
  assertEquals ("pom.xml", p.normalize ().toString ());

  if (WIN)
  {
    // C:\Users\xxx\git\ph-commons\ph-commons\pom.xml
    assertTrue ("Is <" + p.toRealPath ().toString () + ">",
                p.toRealPath ().toString ().endsWith (SEP + "ph-commons" + SEP + "pom.xml"));
  }
  else
  {
    // Gives "cde/../pom.xml" on Linux
    try
    {
      p.toRealPath ();
      fail ();
    }
    catch (final NoSuchFileException ex)
    {
      // expected
    }
  }

  // C:\Users\xxx\git\ph-commons\ph-commons\pom.xml
  assertTrue ("Is <" + p.toAbsolutePath ().toString () + ">",
              p.toAbsolutePath ()
               .toString ()
               .endsWith (SEP + "ph-commons" + SEP + "cde" + SEP + ".." + SEP + "pom.xml"));
}
 
源代码20 项目: ph-commons   文件: PathHelper.java
/**
 * Get the canonical file of the passed file, if the file is not
 * <code>null</code>.
 *
 * @param aFile
 *        The file to get the canonical path from. May be <code>null</code>.
 * @return <code>null</code> if the passed file is <code>null</code>.
 * @throws IOException
 *         If an I/O error occurs, which is possible because the construction
 *         of the canonical pathname may require filesystem queries
 */
@Nullable
public static Path getCanonicalFile (@Nullable final Path aFile) throws IOException
{
  return aFile == null ? null : aFile.toRealPath ();
}