Java Code Examples for java.nio.file.Path#toRealPath()
The following examples show how to use
java.nio.file.Path#toRealPath() .
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: IOUtils.java From lucene-solr with Apache License 2.0 | 6 votes |
/** 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; } }
Example 2
Source File: PathResolver.java From appengine-plugins-core with Apache License 2.0 | 6 votes |
@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); } }
Example 3
Source File: Snapshot.java From raft-java with Apache License 2.0 | 6 votes |
/** * 打开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; }
Example 4
Source File: RegistryImpl.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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]); }
Example 5
Source File: DirectoryOptions.java From synopsys-detect with Apache License 2.0 | 5 votes |
@Nullable private Path toRealPath(@Nullable Path rawPath) throws IOException { if (rawPath == null) { return null; } return rawPath.toRealPath(); }
Example 6
Source File: FileUtil.java From copybara with Apache License 2.0 | 5 votes |
/** * 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); }
Example 7
Source File: SysfsUsbSerialScanner.java From smarthome with Eclipse Public License 2.0 | 5 votes |
/** * 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; } }
Example 8
Source File: PathArguments.java From buck with Apache License 2.0 | 5 votes |
/** * 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()); }
Example 9
Source File: KerberosUtilities.java From qpid-broker-j with Apache License 2.0 | 5 votes |
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); }
Example 10
Source File: SafeFiles.java From util with Apache License 2.0 | 5 votes |
/** * 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(); } }
Example 11
Source File: PathManagerEx.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull public static Path getAppSystemDir() { Path path = Paths.get(ContainerPathManager.get().getSystemPath()); try { return path.toRealPath(); } catch (IOException e) { LOGGER.error(e); } return path; }
Example 12
Source File: FolderReader.java From baleen with Apache License 2.0 | 5 votes |
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); } } }
Example 13
Source File: WriteableUserPath.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
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(); }
Example 14
Source File: AppleDeveloperDirectoryForTestsProviderFactory.java From buck with Apache License 2.0 | 5 votes |
@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)); }
Example 15
Source File: MavenCommand.java From helidon-build-tools with Apache License 2.0 | 5 votes |
/** * 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(); }
Example 16
Source File: WriteableUserPath.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
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(); }
Example 17
Source File: GenericSDKUtils.java From vscode-as3mxml with Apache License 2.0 | 5 votes |
/** * 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; }
Example 18
Source File: ReutersContentSource.java From lucene-solr with Apache License 2.0 | 4 votes |
@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; } }
Example 19
Source File: PathFuncTest.java From ph-commons with Apache License 2.0 | 4 votes |
@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")); }
Example 20
Source File: PathHelper.java From ph-commons with Apache License 2.0 | 2 votes |
/** * 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 (); }