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

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

源代码1 项目: openjdk-jdk8u   文件: APIDeps.java
private static boolean initProfiles() {
    // check if ct.sym exists; if not use the profiles.properties file
    Path home = Paths.get(System.getProperty("java.home"));
    if (home.endsWith("jre")) {
        home = home.getParent();
    }
    Path ctsym = home.resolve("lib").resolve("ct.sym");
    boolean symbolExists = ctsym.toFile().exists();
    if (!symbolExists) {
        Path testSrcProfiles =
            Paths.get(System.getProperty("test.src", "."), "profiles.properties");
        if (!testSrcProfiles.toFile().exists())
            throw new Error(testSrcProfiles + " does not exist");
        System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n",
            ctsym, testSrcProfiles);
        System.setProperty("jdeps.profiles", testSrcProfiles.toString());
    }
    return symbolExists;
}
 
源代码2 项目: jdk8u60   文件: APIDeps.java
private static boolean initProfiles() {
    // check if ct.sym exists; if not use the profiles.properties file
    Path home = Paths.get(System.getProperty("java.home"));
    if (home.endsWith("jre")) {
        home = home.getParent();
    }
    Path ctsym = home.resolve("lib").resolve("ct.sym");
    boolean symbolExists = ctsym.toFile().exists();
    if (!symbolExists) {
        Path testSrcProfiles =
            Paths.get(System.getProperty("test.src", "."), "profiles.properties");
        if (!testSrcProfiles.toFile().exists())
            throw new Error(testSrcProfiles + " does not exist");
        System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n",
            ctsym, testSrcProfiles);
        System.setProperty("jdeps.profiles", testSrcProfiles.toString());
    }
    return symbolExists;
}
 
源代码3 项目: java-swing-tips   文件: MainPanel.java
public static void unzip(Path zipFilePath, Path destDir) throws IOException {
  try (ZipFile zipFile = new ZipFile(zipFilePath.toString())) {
    Enumeration<? extends ZipEntry> e = zipFile.entries();
    while (e.hasMoreElements()) {
      ZipEntry zipEntry = e.nextElement();
      String name = zipEntry.getName();
      Path path = destDir.resolve(name);
      if (name.endsWith("/")) { // if (Files.isDirectory(path)) {
        LOGGER.info(() -> String.format("mkdir1: %s", path));
        Files.createDirectories(path);
      } else {
        Path parent = path.getParent();
        // if (Objects.nonNull(parent) && Files.notExists(parent)) { // noticeably poor performance in JDK 8
        if (Objects.nonNull(parent) && !parent.toFile().exists()) {
          LOGGER.info(() -> String.format("mkdir2: %s", parent));
          Files.createDirectories(parent);
        }
        LOGGER.info(() -> String.format("copy: %s", path));
        Files.copy(zipFile.getInputStream(zipEntry), path, StandardCopyOption.REPLACE_EXISTING);
      }
    }
  }
}
 
源代码4 项目: VocabHunter   文件: FileNameTool.java
private static Path ensureFileHasSuffix(final Path file, final String suffix) {
    String filename = filename(file);

    if (!filename.contains(".")) {
        String newFilename = filename + suffix;
        Path parent = file.getParent();

        if (parent == null) {
            return Paths.get(newFilename);
        } else {
            return parent.resolve(newFilename);
        }
    }

    return file;
}
 
源代码5 项目: promagent   文件: JarFiles.java
private static List<Path> unzip(Path jarFile, Path destDir, Predicate<JarEntry> filter) throws IOException {
    List<Path> result = new ArrayList<>();
    try (JarFile agentJar = new JarFile(jarFile.toFile())) {
        Enumeration<JarEntry> jarEntries = agentJar.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry jarEntry = jarEntries.nextElement();
            if (filter.test(jarEntry)) {
                Path destFile = destDir.resolve(jarEntry.getName());
                if (!destFile.getParent().toFile().exists()) {
                    if (!destFile.getParent().toFile().mkdirs()) {
                        throw new IOException("Failed to make directory: " + destFile.getParent());
                    }
                }
                Files.copy(agentJar.getInputStream(jarEntry), destFile);
                result.add(destFile);
            }
        }
    }
    return result;
}
 
源代码6 项目: testgrid   文件: FileWatcher.java
/**
 * Creates an instance of {@link FileWatcher} to watch the given file.
 *
 * @param watchFile file to be watched
 * @throws FileWatcherException thrown when error on creating an instance of {@link FileWatcher}
 */
public FileWatcher(Path watchFile) throws FileWatcherException {
    // Do not allow this to be a folder since we want to watch files
    if (!Files.isRegularFile(watchFile)) {
        throw new FileWatcherException(StringUtil.concatStrings(watchFile, " is not a regular file."));
    }

    // This is always a folder
    this.folderPath = watchFile.getParent();
    if (this.folderPath == null) {
        throw new FileWatcherException("The path provided do not have a parent. Please provide to complete " +
                                       "path to the file.");
    }

    // Keep this relative to the watched folder
    Path watchFileName = watchFile.getFileName();
    if (watchFileName == null) {
        throw new FileWatcherException("The path has 0 (zero) elements. Please provide a valid file path.");
    }
    this.watchFile = watchFileName.toString();
}
 
源代码7 项目: hottub   文件: APIDeps.java
private static boolean initProfiles() {
    // check if ct.sym exists; if not use the profiles.properties file
    Path home = Paths.get(System.getProperty("java.home"));
    if (home.endsWith("jre")) {
        home = home.getParent();
    }
    Path ctsym = home.resolve("lib").resolve("ct.sym");
    boolean symbolExists = ctsym.toFile().exists();
    if (!symbolExists) {
        Path testSrcProfiles =
            Paths.get(System.getProperty("test.src", "."), "profiles.properties");
        if (!testSrcProfiles.toFile().exists())
            throw new Error(testSrcProfiles + " does not exist");
        System.out.format("%s doesn't exist.%nUse %s to initialize profiles info%n",
            ctsym, testSrcProfiles);
        System.setProperty("jdeps.profiles", testSrcProfiles.toString());
    }
    return symbolExists;
}
 
源代码8 项目: mirror   文件: NativeFileAccess.java
/** @param path the absolute path of the directory to create */
private static void mkdirImpl(Path path) throws IOException {
  path.toFile().mkdirs();
  if (!path.toFile().exists()) {
    // it could be that relative has a parent that used to be a symlink, but now is not anymore...
    boolean foundOldSymlink = false;
    Path current = path;
    while (current != null) {
      if (Files.isSymbolicLink(current)) {
        current.toFile().delete();
        path.toFile().mkdirs();
        foundOldSymlink = true;
      }
      current = current.getParent();
    }
    if (!foundOldSymlink) {
      throw new IOException("Could not create directory " + path + " (" + path.toFile() + " does not exist)");
    }
  }
}
 
源代码9 项目: buck   文件: MorePaths.java
public static Path getParentOrEmpty(Path path) {
  Path parent = path.getParent();
  if (parent == null) {
    parent = emptyOf(path);
  }
  return parent;
}
 
源代码10 项目: buck   文件: ModernBuildRule.java
private static boolean shouldRecord(Set<Path> outputs, Path path) {
  Path parent = path.getParent();
  while (parent != null) {
    if (outputs.contains(parent)) {
      return false;
    }
    parent = parent.getParent();
  }
  return true;
}
 
源代码11 项目: jdk8u-jdk   文件: FileHandler.java
private  boolean isParentWritable(Path path) {
    Path parent = path.getParent();
    if (parent == null) {
        parent = path.toAbsolutePath().getParent();
    }
    return parent != null && Files.isWritable(parent);
}
 
源代码12 项目: ph-commons   文件: PathOperations.java
/**
 * Copies the source file to the target file.
 *
 * @param aSourceFile
 *        The source file to use. May not be <code>null</code>. Needs to be an
 *        existing file.
 * @param aTargetFile
 *        The destination files. May not be <code>null</code> and may not be
 *        an existing file.
 * @return A non-<code>null</code> error code.
 */
@Nonnull
public static FileIOError copyFile (@Nonnull final Path aSourceFile, @Nonnull final Path aTargetFile)
{
  ValueEnforcer.notNull (aSourceFile, "SourceFile");
  ValueEnforcer.notNull (aTargetFile, "TargetFile");

  final Path aRealSourceFile = _getUnifiedPath (aSourceFile);
  final Path aRealTargetFile = _getUnifiedPath (aTargetFile);

  // Does the source file exist?
  if (!aRealSourceFile.toFile ().isFile ())
    return EFileIOErrorCode.SOURCE_DOES_NOT_EXIST.getAsIOError (EFileIOOperation.COPY_FILE, aRealSourceFile);

  // Are source and target different?
  if (EqualsHelper.equals (aRealSourceFile, aRealTargetFile))
    return EFileIOErrorCode.SOURCE_EQUALS_TARGET.getAsIOError (EFileIOOperation.COPY_FILE, aRealSourceFile);

  // Does the target file already exist?
  if (aRealTargetFile.toFile ().exists ())
    return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError (EFileIOOperation.COPY_FILE, aRealTargetFile);

  // Is the source file readable?
  if (!Files.isReadable (aRealSourceFile))
    return EFileIOErrorCode.SOURCE_NOT_READABLE.getAsIOError (EFileIOOperation.COPY_FILE, aRealSourceFile);

  // Is the target parent directory writable?
  final Path aTargetParentDir = aRealTargetFile.getParent ();
  if (aTargetParentDir != null && aTargetParentDir.toFile ().exists () && !Files.isWritable (aTargetParentDir))
    return EFileIOErrorCode.TARGET_PARENT_NOT_WRITABLE.getAsIOError (EFileIOOperation.COPY_FILE, aRealTargetFile);

  // Ensure the targets parent directory is present
  PathHelper.ensureParentDirectoryIsPresent (aRealTargetFile);

  return _perform (EFileIOOperation.COPY_FILE, Files::copy, aRealSourceFile, aRealTargetFile);
}
 
源代码13 项目: jimfs   文件: PathTester.java
private void testStartsWith(Path path) {
  // empty path doesn't start with any path
  if (root != null || !names.isEmpty()) {
    Path other = path;
    while (other != null) {
      assertTrue(path + ".startsWith(" + other + ") should be true", path.startsWith(other));
      assertTrue(
          path + ".startsWith(" + other + ") should be true", path.startsWith(other.toString()));
      other = other.getParent();
    }
  }
}
 
源代码14 项目: jdk8u_jdk   文件: FileHandler.java
private  boolean isParentWritable(Path path) {
    Path parent = path.getParent();
    if (parent == null) {
        parent = path.toAbsolutePath().getParent();
    }
    return parent != null && Files.isWritable(parent);
}
 
源代码15 项目: scelight   文件: XFileChooser.java
@Override
public void setCurrentFolder( Path currentFolder ) {
	while ( currentFolder != null && !Files.exists( currentFolder ) )
		currentFolder = currentFolder.getParent();
	
	if ( currentFolder != null )
		setCurrentDirectory( currentFolder.toFile() );
}
 
源代码16 项目: TencentKona-8   文件: CopyClassFile.java
private static void copyFile(File f) {
    try {
        Path classFilePath = Paths.get(classFile);
        String packagePath = classFilePath.getParent() == null ? "" : classFilePath.getParent().toString();
        Path p = Paths.get(destinationDir + packagePath + File.separator + f.getName());
        Files.createDirectories(p.getParent());
        try (InputStream is = new FileInputStream(f)) {
            Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
        }
    } catch (IOException ex) {
        throw new RuntimeException("Could not copy file " + f, ex);
    }
}
 
源代码17 项目: Singularity   文件: SingularityExecutorCleanup.java
private Iterator<Path> getUncompressedLogrotatedFileIterator(
  SingularityExecutorTaskDefinition taskDefinition
) {
  final Path serviceLogOutPath = taskDefinition.getServiceLogOutPath();
  final Path parent = serviceLogOutPath.getParent();
  if (parent == null) {
    throw new IllegalStateException(
      "Service log path " + serviceLogOutPath + " has no parent"
    );
  }
  final Path logrotateToPath = parent.resolve(
    executorConfiguration.getLogrotateToDirectory()
  );

  if (!logrotateToPath.toFile().exists() || !logrotateToPath.toFile().isDirectory()) {
    LOG.warn(
      "Skipping uncompressed logrotated file cleanup for {} -- {} does not exist or is not a directory (task sandbox was probably garbage collected by Mesos)",
      taskDefinition.getTaskId(),
      logrotateToPath
    );
    return Collections.emptyIterator();
  }

  try {
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(
      logrotateToPath,
      String.format("%s-*", serviceLogOutPath.getFileName())
    );
    return dirStream.iterator();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码18 项目: jmbe   文件: Creator.java
/**
 * Creates a command line classpath of the dependent jar libraries
 *
 * @return concatenated string suitable for -d command line option
 */
public static String getLibraryClassPath()
{
    URL currentURL = Creator.class.getProtectionDomain().getCodeSource().getLocation();
    System.out.println("Current URL:" + currentURL.toString());
    Path currentPath = null;

    try
    {
        currentPath = new File(currentURL.toURI()).toPath();
    }
    catch(Exception e)
    {
        mLog.error("Error discovering current execution path to lookup compile dependencies", e);
        currentPath = null;
    }

    if(currentPath != null && Files.exists(currentPath))
    {
        System.out.println("Discovering: Current Location [" + currentPath.toString() + "]");
        Path parent = currentPath.getParent();
        System.out.println("Discovering: Compile Dependencies [" + parent.toString() + "]");
        StringJoiner joiner = new StringJoiner(String.valueOf(File.pathSeparatorChar));

        try
        {
            DirectoryStream<Path> stream = Files.newDirectoryStream(parent);
            stream.forEach(path -> {
                if(!Files.isDirectory(path) && path.toString().endsWith("jar"))
                {
                    joiner.add(path.toString());
                }
            });
        }
        catch(IOException ioe)
        {
            System.out.println("Failed: Error creating classpath for compile-time libraries - " +
                ioe.getLocalizedMessage());
            ioe.printStackTrace();
            System.exit(EXIT_CODE_IO_ERROR);
        }

        return joiner.toString();
    }

    return "";
}
 
源代码19 项目: archiva   文件: ArtifactBuilderTest.java
StorageAsset getFile(String path) throws IOException {
    Path filePath = Paths.get(path);
    FilesystemStorage filesystemStorage = new FilesystemStorage(filePath.getParent(), new DefaultFileLockManager());
    return new FilesystemAsset(filesystemStorage, filePath.getFileName().toString(), filePath);
}
 
源代码20 项目: Wikidata-Toolkit   文件: MockDirectoryManager.java
/**
 * Sets the contents of the file at the given path and creates all parent
 * directories in our mocked view of the file system. If a compression is
 * chosen, the file contents is the compressed version of the given
 * contents. Strings are encoded as UTF8.
 * <p>
 * This method is used for mocking and is always successful, even if the
 * object is in read-only mode otherwise.
 *
 * @param path
 * @param contents
 * @param compressionType
 * @throws IOException
 */
public void setFileContents(Path path, String contents,
		CompressionType compressionType) throws IOException {
	files.put(path, MockStringContentFactory.getBytesFromString(contents,
			compressionType));
	Path parent = path.getParent();
	if (parent != null) {
		setFileContents(parent, DIRECTORY_MARKER_STRING);
	}
}