Example usage for java.nio.file Path getParent

List of usage examples for java.nio.file Path getParent

Introduction

In this page you can find the example usage for java.nio.file Path getParent.

Prototype

Path getParent();

Source Link

Document

Returns the parent path, or null if this path does not have a parent.

Usage

From source file:org.cryptomator.cryptofs.CryptoFileSystemProviderIntegrationTest.java

@Test
public void testCopyFileByRelacingExistingFromOneCryptoFileSystemToAnother() throws IOException {
    byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
    byte[] data2 = new byte[] { 10, 11, 12 };

    Path fs1Location = tmpPath.resolve("foo");
    Path fs2Location = tmpPath.resolve("bar");
    Files.createDirectories(fs1Location);
    Files.createDirectories(fs2Location);
    FileSystem fs1 = CryptoFileSystemProvider.newFileSystem(fs1Location,
            cryptoFileSystemProperties().withPassphrase("asd").build());
    FileSystem fs2 = CryptoFileSystemProvider.newFileSystem(fs2Location,
            cryptoFileSystemProperties().withPassphrase("qwe").build());
    Path file1 = fs1.getPath("/foo/bar");
    Path file2 = fs2.getPath("/bar/baz");
    Files.createDirectories(file1.getParent());
    Files.createDirectories(file2.getParent());
    Files.write(file1, data);//w  w  w  .j a va 2  s . c o  m
    Files.write(file2, data2);

    Files.copy(file1, file2, REPLACE_EXISTING);

    assertThat(readAllBytes(file1), is(data));
    assertThat(readAllBytes(file2), is(data));
}

From source file:org.dllearner.algorithms.qtl.experiments.EvaluationDataset.java

/**
 * Writes the ID and SPARQL queries line-wise to file.
 *
 * @param file the file//from  w  ww .  j  a  va 2 s.  c om
 */
public void saveToDisk(File file) throws IOException {
    // adjust the PREFIX declarations
    sparqlQueries.entrySet().stream().forEach(entry -> adjustPrefixes(entry.getValue()));

    // create directory and file if not exist
    java.nio.file.Path pathToFile = file.toPath();
    Files.createDirectories(pathToFile.getParent());
    Files.createFile(pathToFile);

    // write ID + queries to disk
    Files.write(pathToFile,
            sparqlQueries.entrySet().stream()
                    .map(entry -> entry.getKey() + ", " + entry.getValue().toString().replace("\n", " "))
                    .collect(Collectors.toList()));
}

From source file:org.openhab.tools.analysis.checkstyle.EshInfXmlValidationCheck.java

private void addToEshFiles(File xmlFile) {
    Path filePath = xmlFile.toPath();
    Path bundlePath = filePath.getParent().getParent().getParent();
    Path relativePath = bundlePath.relativize(filePath);
    eshInfFiles.put(relativePath, xmlFile);
}

From source file:org.canova.sound.recordreader.WavFileRecordReader.java

@Override
public void initialize(InputSplit split) throws IOException, InterruptedException {
    inputSplit = split;/*  w  ww  . j a va  2  s .  c  o  m*/
    if (split instanceof FileSplit) {
        URI[] locations = split.locations();
        if (locations != null && locations.length >= 1) {
            if (locations.length > 1) {
                List<File> allFiles = new ArrayList<>();
                for (URI location : locations) {
                    File iter = new File(location);
                    if (iter.isDirectory()) {
                        Iterator<File> allFiles2 = FileUtils.iterateFiles(iter, null, true);
                        while (allFiles2.hasNext())
                            allFiles.add(allFiles2.next());
                    }

                    else
                        allFiles.add(iter);
                }

                iter = allFiles.iterator();
            } else {
                File curr = new File(locations[0]);
                if (curr.isDirectory())
                    iter = FileUtils.iterateFiles(curr, null, true);
                else
                    iter = Collections.singletonList(curr).iterator();
            }
        }
    }

    else if (split instanceof InputStreamInputSplit) {
        record = new ArrayList<>();
        InputStreamInputSplit split2 = (InputStreamInputSplit) split;
        InputStream is = split2.getIs();
        URI[] locations = split2.locations();
        if (appendLabel) {
            Path path = Paths.get(locations[0]);
            String parent = path.getParent().toString();
            record.add(new DoubleWritable(labels.indexOf(parent)));
        }

        is.close();
    }

}

From source file:org.commonjava.indy.filer.ispn.fileio.StorageFileIO.java

@Override
public void write(MarshalledEntry<? extends String, ? extends byte[]> entry) {
    String key = entry.getKey();//  ww  w . j  a v  a2 s  . c  o m
    logKey("write()", key);

    Path path = Paths.get(storageRoot, key);
    File dir = path.getParent().toFile();
    if (!dir.isDirectory() && !dir.mkdirs()) {
        throw new RuntimeException("Cannot create storage directory: " + dir);
    }

    try (ObjectOutputStream out = new ObjectOutputStream(
            new GZIPOutputStream(new FileOutputStream(path.toFile())))) {
        out.writeObject(new StorageFileEntry(entry));
    } catch (IOException e) {
        throw new RuntimeException("Cannot store: " + path, e);
    }
}

From source file:com.streamsets.pipeline.lib.io.LiveFile.java

/**
 * Refreshes the <code>LiveFile</code>, if the file was renamed, the path will have the new name.
 *
 * @return the refreshed file if the file has been renamed, or itself if the file has not been rename or the file
 * does not exist in the directory anymore.
 * @throws IOException thrown if the LiveFile could not be refreshed
 *//*  w  w  w .j ava2 s. c o m*/
public LiveFile refresh() throws IOException {
    LiveFile refresh = this;
    boolean changed;
    try {
        BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
        String iNodeCurrent = attrs.fileKey().toString();
        int headLenCurrent = (int) Math.min(headLen, attrs.size());
        String headHashCurrent = computeHash(path, headLenCurrent);
        changed = !this.iNode.equals(iNodeCurrent) || !this.headHash.equals(headHashCurrent);
    } catch (NoSuchFileException ex) {
        changed = true;
    }
    if (changed) {

        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path.getParent())) {
            for (Path path : directoryStream) {
                if (path.toFile().isDirectory()) {
                    continue;
                }
                BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
                String iNode = attrs.fileKey().toString();
                int headLen = (int) Math.min(this.headLen, attrs.size());
                String headHash = computeHash(path, headLen);
                if (iNode.equals(this.iNode) && headHash.equals(this.headHash)) {
                    if (headLen == 0) {
                        headLen = (int) Math.min(HEAD_LEN, attrs.size());
                        headHash = computeHash(path, headLen);
                    }
                    return new LiveFile(path, iNode, headHash, headLen);
                } /**rename??*/
            }
        }
        return null;
    } /**change? itself*/
    return refresh;
}

From source file:org.ng200.openolympus.resourceResolvers.OpenOlympusMessageSource.java

private void reportMissingLocalisationKey(final String code) {
    try {/*from  w w w.ja v  a  2s. c o  m*/
        if (code.isEmpty() || Character.isUpperCase(code.charAt(0))) {
            return;
        }
        final Path file = FileSystems.getDefault().getPath(this.storagePath, "missingLocalisation.txt");
        if (!FileAccess.exists(file)) {
            FileAccess.createDirectories(file.getParent());
            FileAccess.createFile(file);
        }
        final Set<String> s = new TreeSet<>(Arrays.asList(FileAccess.readUTF8String(file).split("\n")));
        s.add(code);
        FileAccess.writeUTF8StringToFile(file, s.stream().collect(Collectors.joining("\n")));
    } catch (final IOException e) {
        OpenOlympusMessageSource.logger.error("Couldn't add to missing key repo: {}", e);
    }
}

From source file:com.ejisto.util.visitor.ConditionMatchingCopyFileVisitor.java

private void copy(Path srcFile) throws IOException {
    Path relative = options.srcRoot.relativize(srcFile);
    int count = relative.getNameCount();
    StringBuilder newFileName = new StringBuilder();
    if (count > 1) {
        newFileName.append(relative.getParent().toString());
        newFileName.append(File.separator);
    }/*from  w  w w  . j  a v  a  2  s .co  m*/
    newFileName.append(defaultString(options.filesPrefix)).append(srcFile.getFileName().toString());
    Files.copy(srcFile, options.targetRoot.resolve(newFileName.toString()),
            StandardCopyOption.REPLACE_EXISTING);
}

From source file:br.com.thiaguten.archive.ZipArchive.java

/**
 * Override to make use of the ZipArchive#createArchiveOutputStream(Path path) method
 * instead of the method ZipArchive#createArchiveOutputStream(BufferedOutputStream bufferedOutputStream).
 *///from ww w .ja v  a 2  s .com
@Override
public Path compress(Path... paths) throws IOException {
    Path compress = null;
    ArchiveOutputStream archiveOutputStream = null;

    for (Path path : paths) {
        // get path infos
        final Path parent = path.getParent();
        final String name = path.getFileName().toString();
        final boolean isDirectory = isDirectory(path);

        if (compress == null) {
            // create compress file
            String compressName = (paths.length == 1 ? name : getName());
            compress = Paths.get(parent.toString(), compressName + getExtension());

            // creates a new compress file to not override if already exists
            // if you do not want this behavior, just comment this line
            compress = createFile(ArchiveAction.COMPRESS, parent, compress);

            // open compress file stream
            archiveOutputStream = createArchiveOutputStream(compress);

            logger.debug("creating the archive file " + compressName);
        }

        logger.debug("reading path " + path);

        if (isDirectory) {
            compressDirectory(parent, path, archiveOutputStream);
        } else {
            compressFile(parent, path, archiveOutputStream);
        }
    }

    // closing streams
    if (archiveOutputStream != null) {
        archiveOutputStream.finish();
        archiveOutputStream.close();
    }

    logger.debug("finishing the archive file " + compress);

    return compress;
}

From source file:net.straylightlabs.tivolibre.DecoderApp.java

private Path appendToPath(Path path, String suffix) {
    assert (path != null);
    Path dir = path.getParent();
    Path file = path.getFileName();
    logger.info("dir = '{}', file = '{}'", dir, file);
    if (dir != null) {
        return Paths.get(dir.toString(), file.toString() + suffix);
    } else {/*from ww  w  .  j a va 2  s. co m*/
        return Paths.get(file.toString() + suffix);
    }
}