Example usage for java.nio.file Path getFileName

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

Introduction

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

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by 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");

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

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path sourceFile = Paths.get("C:/home/docs/users.txt");
    Files.move(sourceFile, sourceFile.resolveSibling(sourceFile.getFileName() + ".bak"));

}

From source file:Main.java

public static void main(String[] args) {
    Path path = FileSystems.getDefault().getPath("/home/docs/status.txt");

    System.out.printf("getFileName: %s\n", path.getFileName());
}

From source file:Main.java

public static void main(String[] args) {
    Path copy_from_1 = Paths.get("C:/tutorial/Java/JavaFX", "tutor.txt");

    Path copy_to_1 = Paths.get("C:/tutorial/Java/USOpen", copy_from_1.getFileName().toString());
    try {/* w  w  w  .j  a v  a 2  s  . c  o  m*/
        Files.copy(copy_from_1, copy_to_1, REPLACE_EXISTING, COPY_ATTRIBUTES, NOFOLLOW_LINKS);
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:edu.jhu.hlt.concrete.ingesters.alnc.ALNCIngesterRunner.java

/**
 * @param args/*from   w w w.  j  av a  2 s.  c om*/
 */
public static void main(String... args) {
    Thread.setDefaultUncaughtExceptionHandler(new LoggedUncaughtExceptionHandler());
    ALNCIngesterRunner run = new ALNCIngesterRunner();
    JCommander jc = new JCommander(run, args);
    jc.setProgramName(ALNCIngesterRunner.class.getSimpleName());
    if (run.delegate.help) {
        jc.usage();
    }

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

        for (String pstr : run.delegate.paths) {
            LOGGER.debug("Running on file: {}", pstr);
            Path p = Paths.get(pstr);
            new ExistingNonDirectoryFile(p);
            Path outWithExt = outpath.resolve(p.getFileName() + ".tar.gz");

            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 (ALNCIngester ing = new ALNCIngester(p);
                    OutputStream os = Files.newOutputStream(outWithExt);
                    GzipCompressorOutputStream gout = new GzipCompressorOutputStream(os);
                    TarArchiver arch = new TarArchiver(gout)) {
                Iterator<Communication> iter = ing.iterator();
                while (iter.hasNext()) {
                    Communication c = iter.next();
                    LOGGER.debug("Got comm: {}", c.getId());
                    arch.addEntry(new ArchivableCommunication(c));
                }
            } catch (IngestException e) {
                LOGGER.error("Caught exception processing path: " + pstr, e);
            }
        }
    } catch (NotFileException | IOException e) {
        LOGGER.error("Caught exception processing.", e);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path sourceFile = FileSystems.getDefault().getPath("C:/home/docs/users.txt");
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Files.copy(sourceFile, outputStream);
    byte arr[] = outputStream.toByteArray();
    System.out.println("The contents of " + sourceFile.getFileName());
    for (byte data : arr) {
        System.out.print((char) data);
    }//from  w w  w . ja  v a 2s  .  c o  m

}

From source file:listfiles.ListFiles.java

/**
 * @param args the command line arguments
 *///w  ww. j  a v  a 2s  .co  m
public static void main(String[] args) {
    // TODO code application logic here
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String folderPath = "";
    String fileName = "DirectoryFiles.xlsx";

    try {
        System.out.println("Folder path :");
        folderPath = reader.readLine();
        //System.out.println("Output File Name :");
        //fileName = reader.readLine();

        XSSFWorkbook wb = new XSSFWorkbook();
        FileOutputStream fileOut = new FileOutputStream(folderPath + "\\" + fileName);
        XSSFSheet sheet1 = wb.createSheet("Files");
        int row = 0;
        Stream<Path> stream = Files.walk(Paths.get(folderPath));
        Iterator<Path> pathIt = stream.iterator();
        String ext = "";

        while (pathIt.hasNext()) {
            Path filePath = pathIt.next();
            Cell cell1 = checkRowCellExists(sheet1, row, 0);
            Cell cell2 = checkRowCellExists(sheet1, row, 1);
            row++;
            ext = FilenameUtils.getExtension(filePath.getFileName().toString());
            cell1.setCellValue(filePath.getFileName().toString());
            cell2.setCellValue(ext);

        }
        sheet1.autoSizeColumn(0);
        sheet1.autoSizeColumn(1);

        wb.write(fileOut);
        fileOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("Program Finished");
}

From source file:net.tirasa.ilgrosso.lngenerator.Main.java

public static void main(final String[] args) throws IOException, URISyntaxException {
    assert args.length > 0 : "No arguments provided";

    File source = new File(args[0]);
    if (!source.isDirectory()) {
        throw new IllegalArgumentException("Not a directory: " + args[0]);
    }//w w  w . j  a v  a  2s.c  o  m

    String destPath = args.length > 1 ? args[1] : System.getProperty("java.io.tmpdir");
    File dest = new File(destPath);
    if (!dest.isDirectory() || !dest.canWrite()) {
        throw new IllegalArgumentException("Not a directory, or not writable: " + destPath);
    }

    LOG.debug("Local Maven repo is {}", LOCAL_M2_REPO);
    LOG.debug("Source Path is {}", source.getAbsolutePath());
    LOG.debug("Destination Path is {}", dest.getAbsolutePath());
    LOG.warn("Existing LICENSE and NOTICE files in {} will be overwritten!", dest.getAbsolutePath());

    Set<String> keys = new HashSet<>();

    Files.walk(source.toPath()).filter(Files::isRegularFile)
            .map((final Path path) -> path.getFileName().toString())
            .filter((String path) -> path.endsWith(".jar")).sorted().forEach((filename) -> {
                try (Stream<Path> stream = Files.find(LOCAL_M2_REPO_PATH, 10,
                        (path, attr) -> String.valueOf(path.getFileName().toString()).equals(filename))) {

                    String fullPath = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
                    if (fullPath.isEmpty()) {
                        LOG.warn("Could not find {} in the local Maven repo", filename);
                    } else {
                        String path = fullPath.substring(LOCAL_M2_REPO.length() + 1);
                        Gav gav = GAV_CALCULATOR.pathToGav(path);
                        if (gav == null) {
                            LOG.error("Invalid Maven path: {}", path);
                        } else if (!gav.getGroupId().startsWith("org.apache.")
                                && !gav.getGroupId().startsWith("commons-")
                                && !gav.getGroupId().equals("org.codehaus.groovy")
                                && !gav.getGroupId().equals("jakarta-regexp")
                                && !gav.getGroupId().equals("xml-apis") && !gav.getGroupId().equals("batik")) {

                            if (ArrayUtils.contains(CONSOLIDATING_GROUP_IDS, gav.getGroupId())) {
                                keys.add(gav.getGroupId());
                            } else if (gav.getGroupId().startsWith("com.fasterxml.jackson")) {
                                keys.add("com.fasterxml.jackson");
                            } else if (gav.getGroupId().equals("org.webjars.bower") && (gav.getArtifactId()
                                    .startsWith("angular-animate")
                                    || gav.getArtifactId().startsWith("angular-cookies")
                                    || gav.getArtifactId().startsWith("angular-resource")
                                    || gav.getArtifactId().startsWith("angular-sanitize")
                                    || gav.getArtifactId().startsWith("angular-treasure-overlay-spinner"))) {

                                keys.add("org.webjars.bower:angular");
                            } else if (gav.getGroupId().equals("org.webjars.bower")
                                    && gav.getArtifactId().startsWith("angular-translate")) {

                                keys.add("org.webjars.bower:angular-translate");
                            } else if (gav.getGroupId().startsWith("de.agilecoders")) {
                                keys.add("wicket-bootstrap");
                            } else if ("org.webjars".equals(gav.getGroupId())) {
                                if (gav.getArtifactId().startsWith("jquery-ui")) {
                                    keys.add("jquery-ui");
                                } else {
                                    keys.add(gav.getArtifactId());
                                }
                            } else {
                                keys.add(gav.getGroupId() + ":" + gav.getArtifactId());
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.error("While looking for Maven artifacts from the local Maven repo", e);
                }
            });

    final Properties licenses = new Properties();
    licenses.loadFromXML(Main.class.getResourceAsStream("/licenses.xml"));

    final Properties notices = new Properties();
    notices.loadFromXML(Main.class.getResourceAsStream("/notices.xml"));

    BufferedWriter licenseWriter = Files.newBufferedWriter(new File(dest, "LICENSE").toPath(),
            StandardOpenOption.CREATE);
    licenseWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/LICENSE.template").toURI()))));

    BufferedWriter noticeWriter = Files.newBufferedWriter(new File(dest, "NOTICE").toPath(),
            StandardOpenOption.CREATE);
    noticeWriter.write(
            new String(Files.readAllBytes(Paths.get(Main.class.getResource("/NOTICE.template").toURI()))));

    EnumSet<LICENSE> outputLicenses = EnumSet.noneOf(LICENSE.class);

    keys.stream().sorted().forEach((final String dependency) -> {
        if (licenses.getProperty(dependency) == null) {
            LOG.error("Could not find license information about {}", dependency);
        } else {
            try {
                licenseWriter.write("\n==\n\nFor " + licenses.getProperty(dependency) + ":\n");

                String depLicense = licenses.getProperty(dependency + ".license");
                if (depLicense == null) {
                    licenseWriter.write("This is licensed under the AL 2.0, see above.");
                } else {
                    LICENSE license = LICENSE.valueOf(depLicense);

                    if (license == LICENSE.PUBLIC_DOMAIN) {
                        licenseWriter.write("This is " + license.getLabel() + ".");
                    } else {
                        licenseWriter.write("This is licensed under the " + license.getLabel());

                        if (outputLicenses.contains(license)) {
                            licenseWriter.write(", see above.");
                        } else {
                            outputLicenses.add(license);

                            licenseWriter.write(":\n\n");
                            licenseWriter.write(new String(Files.readAllBytes(
                                    Paths.get(Main.class.getResource("/LICENSE." + license.name()).toURI()))));
                        }
                    }
                }
                licenseWriter.write('\n');

                if (notices.getProperty(dependency) != null) {
                    noticeWriter.write("\n==\n\n" + notices.getProperty(dependency) + "\n");
                }
            } catch (Exception e) {
                LOG.error("While dealing with {}", dependency, e);
            }
        }
    });

    licenseWriter.close();
    noticeWriter.close();

    LOG.debug("Execution completed successfully, look at {} for the generated LICENSE and NOTICE files",
            dest.getAbsolutePath());
}

From source file:Main.java

public static void main(String[] args) {
    DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
        public boolean accept(Path file) throws IOException {
            return (Files.isHidden(file));
        }/*w w  w. j  a va 2s  . co  m*/
    };
    Path directory = Paths.get("C:/Windows");
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory, filter)) {
        for (Path file : directoryStream) {
            System.out.println(file.getFileName());
        }
    } catch (IOException | DirectoryIteratorException ex) {
        ex.printStackTrace();
    }
}

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

/**
 * @param args//from   ww w  .  j a va 2 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);
    }
}