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:Main.java

public static void main(String[] args) {

    Path path = Paths.get("C:", "tutorial/Java/JavaFX", "Topic.txt");

    System.out.println(path.getNameCount());

}

From source file:Main.java

public static void main(String[] args) {

    Path path = Paths.get("C:", "tutorial/Java/JavaFX", "Topic.txt");

    for (int i = 0; i < path.getNameCount(); i++) {
        System.out.println("Name element " + i + " is: " + path.getName(i));
    }//from w  w  w  .j  av  a 2s  .  c om
}

From source file:Test.java

public static void main(String[] args) {
    Path path = FileSystems.getDefault().getPath("/home/docs/status.txt");
    System.out.printf("getNameCount: %d\n", path.getNameCount());
    for (int index = 0; index < path.getNameCount(); index++) {
        System.out.printf("getName(%d): %s\n", index, path.getName(index));
    }// w  w  w . ja va  2  s.  c  o m
}

From source file:edu.jhu.hlt.concrete.ingesters.annotatednyt.AnnotatedNYTIngesterRunner.java

/**
 * @param args//from ww w.ja v  a  2s .c  o  m
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    AnnotatedNYTIngesterRunner run = new AnnotatedNYTIngesterRunner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(AnnotatedNYTIngesterRunner.class.getSimpleName());
    if (run.delegate.help) {
        jc.usage();
    }

    try {
        Path outpath = Paths.get(run.delegate.outputPath);
        IngesterParameterDelegate.prepare(outpath);

        NYTCorpusDocumentParser parser = new NYTCorpusDocumentParser();
        for (String pstr : run.delegate.paths) {
            LOGGER.debug("Running on file: {}", pstr);
            Path p = Paths.get(pstr);
            new ExistingNonDirectoryFile(p);
            int nPaths = p.getNameCount();
            Path year = p.getName(nPaths - 2);
            Path outWithExt = outpath.resolve(year.toString() + p.getFileName());

            if (Files.exists(outWithExt)) {
                if (!run.delegate.overwrite) {
                    LOGGER.info("File: {} exists and overwrite disabled. Not running.", outWithExt.toString());
                    continue;
                } else {
                    Files.delete(outWithExt);
                }
            }

            try (InputStream is = Files.newInputStream(p);
                    BufferedInputStream bin = new BufferedInputStream(is);
                    TarGzArchiveEntryByteIterator iter = new TarGzArchiveEntryByteIterator(bin);

                    OutputStream os = Files.newOutputStream(outWithExt);
                    GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                    TarArchiver arch = new TarArchiver(gout)) {
                Iterable<byte[]> able = () -> iter;
                StreamSupport.stream(able.spliterator(), false).map(ba -> parser.fromByteArray(ba, false))
                        .map(doc -> new AnnotatedNYTDocument(doc))
                        .map(and -> new CommunicationizableAnnotatedNYTDocument(and).toCommunication())
                        .forEach(comm -> {
                            try {
                                arch.addEntry(new ArchivableCommunication(comm));
                            } catch (IOException e) {
                                LOGGER.error("Caught exception processing file: " + pstr, e);
                            }
                        });
            }
        }
    } catch (NotFileException | IOException e) {
        LOGGER.error("Caught exception processing.", e);
    }
}

From source file:at.spardat.xma.xdelta.JarPatcher.java

/**
 * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at
 * the command line.<br>//from   w  w w . j  av a 2s.c o m
 * usage JarPatcher source patch output
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    String patchName = null;
    String outputName = null;
    String sourceName = null;
    if (args.length == 0) {
        System.err.println("usage JarPatcher patch [output [source]]");
        System.exit(1);
    } else {
        patchName = args[0];
        if (args.length > 1) {
            outputName = args[1];
            if (args.length > 2) {
                sourceName = args[2];
            }
        }
    }
    ZipFile patch = new ZipFile(patchName);
    ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list");
    if (listEntry == null) {
        System.err.println("Invalid patch - list entry 'META-INF/file.list' not found");
        System.exit(2);
    }
    BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry)));
    String next = list.readLine();
    if (sourceName == null) {
        sourceName = next;
    }
    next = list.readLine();
    if (outputName == null) {
        outputName = next;
    }
    int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0"));
    int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0"));
    Path sourcePath = Paths.get(sourceName);
    Path outputPath = Paths.get(outputName);
    if (ignoreOutputPaths >= outputPath.getNameCount()) {
        patch.close();
        StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (")
                .append(ignoreOutputPaths).append(" in ").append(outputName).append(")");
        throw new IOException(b.toString());
    }
    if (ignoreSourcePaths >= sourcePath.getNameCount()) {
        patch.close();
        StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (")
                .append(sourcePath).append(" in ").append(sourceName).append(")");
        throw new IOException(b.toString());
    }
    sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount());
    outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount());
    File sourceFile = sourcePath.toFile();
    File outputFile = outputPath.toFile();
    if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs()
            || outputFile.getAbsoluteFile().getParentFile().exists())) {
        patch.close();
        throw new IOException("Failed to create " + outputFile.getAbsolutePath());
    }
    new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile),
            new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list);
    list.close();
}

From source file:edu.jhu.hlt.concrete.gigaword.expt.ConvertGigawordDocuments.java

/**
 * @param args//from   www. jav  a 2s .c o  m
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.error("Thread {} caught unhandled exception.", t.getName());
            logger.error("Unhandled exception.", e);
        }
    });

    if (args.length != 2) {
        logger.info("Usage: {} {} {}", GigawordConcreteConverter.class.getName(), "path/to/expt/file",
                "path/to/out/folder");
        System.exit(1);
    }

    String exptPathStr = args[0];
    String outPathStr = args[1];

    // Verify path points to something.
    Path exptPath = Paths.get(exptPathStr);
    if (!Files.exists(exptPath)) {
        logger.error("File: {} does not exist. Re-run with the correct path to "
                + " the experiment 2 column file. See README.md.");
        System.exit(1);
    }

    logger.info("Experiment map located at: {}", exptPathStr);

    // Create output dir if not yet created.
    Path outPath = Paths.get(outPathStr);
    if (!Files.exists(outPath)) {
        logger.info("Creating directory: {}", outPath.toString());
        try {
            Files.createDirectories(outPath);
        } catch (IOException e) {
            logger.error("Caught an IOException when creating output dir.", e);
            System.exit(1);
        }
    }

    logger.info("Output directory located at: {}", outPathStr);

    // Read in expt map. See README.md.
    Map<String, Set<String>> exptMap = null;
    try (Reader r = ExperimentUtils.createReader(exptPath); BufferedReader br = new BufferedReader(r)) {
        exptMap = ExperimentUtils.createFilenameToIdMap(br);
    } catch (IOException e) {
        logger.error("Caught an IOException when creating expt map.", e);
        System.exit(1);
    }

    // Start a timer.
    logger.info("Gigaword -> Concrete beginning.");
    StopWatch sw = new StopWatch();
    sw.start();
    // Iterate over expt map.
    exptMap.entrySet()
            // .parallelStream()
            .forEach(p -> {
                final String pathStr = p.getKey();
                final Set<String> ids = p.getValue();
                final Path lp = Paths.get(pathStr);
                logger.info("Converting path: {}", pathStr);

                // Get the file name and immediate folder it is under.
                int nElements = lp.getNameCount();
                Path fileName = lp.getName(nElements - 1);
                Path subFolder = lp.getName(nElements - 2);
                String newFnStr = fileName.toString().split("\\.")[0] + ".tar";

                // Mirror folders in output dir.
                Path localOutFolder = outPath.resolve(subFolder);
                Path localOutPath = localOutFolder.resolve(newFnStr);

                // Create output subfolders.
                if (!Files.exists(localOutFolder) && !Files.isDirectory(localOutFolder)) {
                    logger.info("Creating out file: {}", localOutFolder.toString());
                    try {
                        Files.createDirectories(localOutFolder);
                    } catch (IOException e) {
                        throw new RuntimeException("Caught an IOException when creating output dir.", e);
                    }
                }

                // Iterate over communications.
                Iterator<Communication> citer;
                try (OutputStream os = Files.newOutputStream(localOutPath);
                        BufferedOutputStream bos = new BufferedOutputStream(os);
                        Archiver archiver = new TarArchiver(bos);) {
                    citer = new ConcreteGigawordDocumentFactory().iterator(lp);
                    while (citer.hasNext()) {
                        Communication c = citer.next();
                        String cId = c.getId();

                        // Document ID must be in the set. Remove.
                        boolean wasInSet = ids.remove(cId);
                        if (!wasInSet) {
                            // Some IDs are duplicated in Gigaword.
                            // See ERRATA.
                            logger.debug(
                                    "ID: {} was parsed from path: {}, but was not in the experiment map. Attempting to remove dupe.",
                                    cId, pathStr);

                            // Attempt to create a duplicate id (append .duplicate to the id).
                            // Then, try to remove again.
                            String newId = RepairDuplicateIDs.repairDuplicate(cId);
                            boolean dupeRemoved = ids.remove(newId);
                            // There are not nested duplicates, so this should never fire.
                            if (!dupeRemoved) {
                                logger.info("Failed to remove dupe.");
                                return;
                            } else
                                // Modify the communication ID to the unique version.
                                c.setId(newId);
                        }

                        archiver.addEntry(new ArchivableCommunication(c));
                    }

                    logger.info("Finished path: {}", pathStr);
                } catch (ConcreteException ex) {
                    logger.error("Caught ConcreteException during Concrete mapping.", ex);
                    logger.error("Path: {}", pathStr);
                } catch (IOException e) {
                    logger.error("Error archiving communications.", e);
                    logger.error("Path: {}", localOutPath.toString());
                }
            });

    sw.stop();
    logger.info("Finished.");
    Minutes m = new Duration(sw.getTime()).toStandardMinutes();
    logger.info("Runtime: Approximately {} minutes.", m.getMinutes());
}

From source file:Main.java

public static void printDetails(Path p) {
    System.out.println("Details for path: " + p);

    int count = p.getNameCount();
    System.out.println("Name count: " + count);

    for (int i = 0; i < count; i++) {
        Path name = p.getName(i);
        System.out.println("Name at  index   " + i + "  is " + name);
    }//from  w  w  w .  ja v a 2s.c o  m

    Path parent = p.getParent();
    Path root = p.getRoot();
    Path fileName = p.getFileName();
    System.out.println("Parent: " + parent + ", Root:   " + root + ", File Name: " + fileName);
    System.out.println("Absolute Path: " + p.isAbsolute());
}

From source file:onl.area51.httpd.util.ContentTypeResolver.java

public static ContentType resolve(Path p) {
    return resolve(p == null ? null : p.getName(p.getNameCount() - 1).toString());
}

From source file:com.blackducksoftware.integration.hub.detect.workflow.codelocation.FileNameUtils.java

public static String relativize(final String from, final String to) {
    String relative = to;//from   ww w  .  j  a  va  2s. co m
    try {
        final Path toPath = new File(to).toPath();
        final Path fromPath = new File(from).toPath();
        final Path fromParentPath = fromPath.getParent();
        final Path relativePath = fromParentPath.relativize(toPath);
        final List<String> relativePieces = new ArrayList<>();
        for (int i = 0; i < relativePath.getNameCount(); i++) {
            relativePieces.add(relativePath.getName(i).toFile().getName());
        }
        relative = StringUtils.join(relativePieces, "/");
    } catch (final Exception e) {
        logger.info(String.format("Unable to relativize path, full source path will be used: %s", to));
        logger.debug("The reason relativize failed: ", e);
    }

    return relative;
}

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

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