Example usage for java.nio.file Path getName

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

Introduction

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

Prototype

Path getName(int index);

Source Link

Document

Returns a name element of this path as a Path object.

Usage

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));
    }//w  ww .ja va2s  . com
}

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 . j a  va 2s  .  c om
}

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

/**
 * @param args/*  ww w . ja va2 s .  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:edu.jhu.hlt.concrete.gigaword.expt.ConvertGigawordDocuments.java

/**
 * @param args// w  w  w  .  j a va2 s .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: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: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 .j  av a2  s . co  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: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  w w  .ja v a 2s. co  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.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;/* ww  w.  jav  a2  s  .  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: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  a v  a 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.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;// www. ja  v  a 2s .  c o  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);
    }
}