Example usage for java.nio.file Path getNameCount

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

Introduction

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

Prototype

int getNameCount();

Source Link

Document

Returns the number of name elements in the path.

Usage

From source file:com.github.blindpirate.gogradle.util.StringUtils.java

public static Stream<String> eachSubPathReverse(String packagePath) {
    Path path = Paths.get(packagePath);
    return IntStream.range(0, path.getNameCount()).mapToObj(i -> path.subpath(0, path.getNameCount() - i))
            .map(StringUtils::toUnixString);
}

From source file:com.textocat.textokit.commons.io.IoUtils.java

public static Path addExtension(Path srcPath, String newExt) {
    Preconditions.checkArgument(newExt != null, "extension is null");
    if (srcPath.getNameCount() == 0) {
        return srcPath;
    }//ww w  . jav a2s. co m
    String filename = srcPath.getFileName().toString();
    return srcPath.resolveSibling(filename + "." + newExt);
}

From source file:io.crate.testing.Utils.java

static void uncompressTarGZ(File tarFile, File dest) throws IOException {
    TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tarFile))));

    TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
    // tarIn is a TarArchiveInputStream
    while (tarEntry != null) {
        Path entryPath = Paths.get(tarEntry.getName());

        if (entryPath.getNameCount() == 1) {
            tarEntry = tarIn.getNextTarEntry();
            continue;
        }/*from   w  w w.  ja  v  a2 s . co m*/

        Path strippedPath = entryPath.subpath(1, entryPath.getNameCount());
        File destPath = new File(dest, strippedPath.toString());

        if (tarEntry.isDirectory()) {
            destPath.mkdirs();
        } else {
            destPath.createNewFile();
            byte[] btoRead = new byte[1024];
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
            int len;
            while ((len = tarIn.read(btoRead)) != -1) {
                bout.write(btoRead, 0, len);
            }

            bout.close();
            if (destPath.getParent().equals(dest.getPath() + "/bin")) {
                destPath.setExecutable(true);
            }
        }
        tarEntry = tarIn.getNextTarEntry();
    }
    tarIn.close();
}

From source file:org.apromore.tools.cpfimporter.Import.java

private static int getFolderId(final File file) {
    final String user = "ad1f7b60-1143-4399-b331-b887585a0f30";

    List<FolderType> tree = manager.getWorkspaceFolderTree(user);
    Path path = file.toPath();

    FolderType folder;/*from  ww  w.  j  a  v a2s.c  o m*/
    int id = 0;
    for (int i = 0; i < path.getNameCount(); i++) {
        folder = findFolderByName(path.getName(i).toString(), tree);
        if (folder == null) {
            return -1;
        }
        tree = folder.getFolders();
        id = folder.getId();
    }
    return id;
}

From source file:se.kth.climate.fast.netcdfparquet.Main.java

private static File[] findFiles(String[] fileNames) {
    ArrayList<File> files = new ArrayList<>();
    for (String fileName : fileNames) {
        if (fileName.contains("*")) {
            String[] parts = fileName.split("\\*");
            if (parts.length > 2) {
                LOG.error("Only a single file wildcard ist supported! (in {} -> {})", fileName,
                        Arrays.toString(parts));
                System.exit(1);//from   w ww .ja  v a  2 s . c  o  m
            }
            Path filePath = FileSystems.getDefault().getPath(parts[0]);
            String filePrefix = filePath.getName(filePath.getNameCount() - 1).toString();
            Path directoryPath = filePath.getParent();
            if (directoryPath == null) {
                directoryPath = FileSystems.getDefault().getPath(".");
            }
            directoryPath = directoryPath.normalize();
            File dir = directoryPath.toFile();
            if (dir.exists() && dir.isDirectory() && dir.canRead()) {

                FileFilter fileFilter;
                if (parts.length == 1) {
                    fileFilter = new WildcardFileFilter(filePrefix + "*");
                } else {
                    fileFilter = new WildcardFileFilter(filePrefix + "*" + parts[1]);
                }
                File[] matches = dir.listFiles(fileFilter);
                for (File f : matches) {
                    files.add(f);
                }
            } else {
                LOG.error("Can't access {} properly!", dir);
                System.exit(1);
            }
        } else {
            files.add(new File(fileName));
        }
    }
    return files.toArray(new File[0]);
}

From source file:org.mitre.mpf.wfm.service.component.StartupComponentRegistrationServiceImpl.java

private static String getPackageTld(Path componentPackage) {
    try (TarArchiveInputStream inputStream = new TarArchiveInputStream(
            new GZIPInputStream(Files.newInputStream(componentPackage)))) {
        TarArchiveEntry tarEntry;//from  ww  w. j av a 2s .  co m
        while ((tarEntry = inputStream.getNextTarEntry()) != null) {
            Path entryPath = Paths.get(tarEntry.getName());
            if (entryPath.getNameCount() > 0) {
                return entryPath.getName(0).toString();
            }
        }
        return null;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:jvmoptions.OptionAnalyzer.java

static Map<String, Map<String, String>> parse(Path hpp) {
    System.out.printf("process %s %n", hpp);
    String file = hpp.subpath(4, hpp.getNameCount()).toString().replace(File.separatorChar, '/');
    try {/*from   w  ww  . j  a  va2 s . co  m*/
        String all = preprocess(hpp);

        String categories = "(?<kind>develop|develop_pd|product|product_pd|diagnostic|experimental|notproduct|manageable|product_rw|lp64_product)";

        // detect Regex bugs.
        List<String> names = parseNames(all, categories);
        Set<String> nameSet = new HashSet<>();

        Pattern descPtn = Pattern.compile("\"((\\\\\"|[^\"])+)\"");
        Pattern pattern = Pattern.compile(categories
                + "\\((?<type>\\w+?),[ ]*(?<name>\\w+)[ ]*(,[ ]*(?<default>[\\w ()\\-+/*.\"]+))?,[ ]*(?<desc>("
                + descPtn.pattern() + "[ ]*)+)\\)");

        Map<String, Map<String, String>> result = new HashMap<>();

        int times = 0;
        for (Matcher matcher = pattern.matcher(all); matcher.find(); times++) {
            String name = matcher.group("name");
            verify(names, nameSet, times, name);

            String def = Objects.toString(matcher.group("default"), "");

            String d = matcher.group("desc");
            StringBuilder desc = new StringBuilder();
            for (Matcher m = descPtn.matcher(d); m.find();) {
                desc.append(m.group(1).replaceAll("\\\\", ""));
            }

            Map<String, String> m = new HashMap<>();
            m.put("kind", matcher.group("kind"));
            m.put("type", matcher.group("type"));
            m.put("default", def);
            m.put("description", desc.toString());
            m.put("file", file);
            result.put(name, m);
        }
        System.out.printf("        %s contains %d options%n", hpp, times);

        return result;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.dataconservancy.dcs.util.FilePathUtil.java

/**
 * This method checks whether a file path contains any illegal characters.
 * @param file the file to check/*from  w w  w  .  j av a  2 s . c o  m*/
 * @return boolean true if the path is OK, false otherwise
 */
public static boolean hasValidFilePath(File file) {
    Path path = file.toPath();
    for (int i = 0; i < path.getNameCount(); i++) {
        if (StringUtils.containsAny(path.getName(i).toString(), getCharacterBlackList())) {
            return false;
        }
    }
    return true;
}

From source file:org.darkware.wpman.config.ReloadableWordpressConfig.java

/**
 * Parse the filename of the given path to extract a slug. The slug is defined as all text leading up to
 * the filename extension./*  w  w  w. j ava 2 s  .  c o  m*/
 *
 * @param file The path to extract a slug from.
 * @return The slug, as a {@code String}
 * @throws IllegalSlugException If the extracted portion of the filename is illegal for a slug.
 */
private static String slugForFile(final Path file) {
    String filename = file.getName(file.getNameCount() - 1).toString();
    int extStart = filename.lastIndexOf('.');

    String slug;
    if (extStart == -1)
        slug = filename;
    else
        slug = filename.substring(0, extStart);

    // Do some verification
    if (slug.length() < 1)
        throw new IllegalSlugException(slug);
    if (slug.contains(".") || slug.contains(" "))
        throw new IllegalSlugException(slug);

    return slug;
}

From source file:org.dataconservancy.packaging.tool.impl.generator.RemediationUtil.java

/**
 * Generate a unique path for {@code node} based on the suggested location.
 *
 * @param node the node//ww w . j a  v a  2  s .  c om
 * @param locationHint the suggested location
 * @return the unique location based on the node and the hint
 */
static String unique(Node node, String locationHint) throws URISyntaxException {
    final Path path = Paths.get(locationHint);
    final StringBuilder remediatedPath = new StringBuilder();

    if (path.toString().startsWith(File.separator)) {
        remediatedPath.append("/");
    }

    if (path.getNameCount() > 1) {
        remediatedPath.append(path.subpath(0, path.getNameCount() - 1).toString());
        remediatedPath.append("/");
    }

    final StringBuilder toRemediate = new StringBuilder(shaHex(node.getIdentifier().toString()));

    remediatedPath.append(toRemediate);

    if (locationHint.endsWith("/")) {
        remediatedPath.append("/");
    }

    return remediatedPath.toString().replace(File.separatorChar, '/');
}