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:com.nsn.squirrel.tab.utils.PathUtils.java

/**
 * Root path have no file name./* w w  w  . j  a v  a2s . c o  m*/
 * 
 * @param path
 * @return file name
 */
public static String getFileName(Path path) {

    String pathString = null;
    if (path != null) {
        if (path.getFileName() != null) {
            pathString = path.getFileName().toString();
        } else {
            pathString = path.toString();
        }
    }
    return pathString;
}

From source file:hrytsenko.gscripts.io.CsvFiles.java

/**
 * Load records from file.//w ww.  ja  v  a  2s .c om
 * 
 * @param args
 *            the named arguments.
 * 
 * @return the list of text records.
 * 
 * @throws AppException
 *             if file could not be loaded.
 */
public static List<Map<String, String>> loadCsv(Map<String, ?> args) {
    Path path = NamedArgs.findPath(args);
    LOGGER.info("Load {}.", path.getFileName());

    CsvSchema schema = schemaFrom(args).setUseHeader(true).build();

    try (InputStream dataStream = Files.newInputStream(path);
            InputStream bomStream = new BOMInputStream(dataStream);
            Reader dataReader = new InputStreamReader(bomStream, charsetFrom(args))) {
        CsvMapper mapper = new CsvMapper();
        ObjectReader reader = mapper.readerFor(Map.class).with(schema);
        return Lists.newArrayList(reader.readValues(dataReader));
    } catch (Exception exception) {
        throw new AppException(String.format("Could not load file %s.", path.getFileName()), exception);
    }
}

From source file:cane.brothers.e4.commander.utils.PathUtils.java

/**
 * Root path have no file name./*from   w ww.j a  va2 s .c o m*/
 * 
 * TODO rework extra symbols
 * 
 * @param path
 * @return file name
 */
public static String getFileName(Path path) {
    String pathString = null;
    if (path != null) {
        if (path.getFileName() != null) {
            pathString = path.getFileName().toString();
        } else {
            pathString = path.toString();
        }
    }
    return pathString;
}

From source file:hrytsenko.gscripts.io.CsvFiles.java

/**
 * Save records into file.// ww  w .  j av  a2s.c  om
 * 
 * <p>
 * If file already exists, then it will be overridden.
 * 
 * @param records
 *            the list of records to save.
 * @param args
 *            the named arguments.
 * 
 * @throws IOException
 *             if file could not be saved.
 */
public static void saveCsv(List<Map<String, ?>> records, Map<String, ?> args) {
    if (records.isEmpty()) {
        LOGGER.info("No records to save.");
        return;
    }

    Path path = NamedArgs.findPath(args);
    LOGGER.info("Save {}.", path.getFileName());

    CsvSchema.Builder csvSchema = schemaFrom(args).setUseHeader(true);
    Records.columns(records).forEach(csvSchema::addColumn);

    try (Writer writer = Files.newBufferedWriter(path, charsetFrom(args))) {
        CsvMapper csvMapper = new CsvMapper();
        csvMapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);

        csvMapper.writer().with(csvSchema.build()).writeValue(writer, Records.normalize(records));
    } catch (IOException exception) {
        throw new AppException(String.format("Could not save file %s.", path.getFileName()), exception);
    }
}

From source file:net.minecrell.quartz.launch.mappings.MappingsLoader.java

public static Mappings load(Logger logger) throws IOException {
    URI source;//from   w  w w. j av  a 2s.c o  m
    try {
        source = requireNonNull(Mapping.class.getProtectionDomain().getCodeSource(),
                "Unable to find class source").getLocation().toURI();
    } catch (URISyntaxException e) {
        throw new IOException("Failed to find class source", e);
    }

    Path location = Paths.get(source);
    logger.debug("Mappings location: {}", location);

    List<ClassNode> mappingClasses = new ArrayList<>();

    // Load the classes from the source
    if (Files.isDirectory(location)) {
        // We're probably in development environment or something similar
        // Search for the class files
        Files.walkFileTree(location.resolve(PACKAGE), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    try (InputStream in = Files.newInputStream(file)) {
                        ClassNode classNode = MappingsParser.loadClassStructure(in);
                        mappingClasses.add(classNode);
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        // Go through the JAR file
        try (ZipFile zip = new ZipFile(location.toFile())) {
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String name = StringUtils.removeStart(entry.getName(), MAPPINGS_DIR);
                if (entry.isDirectory() || !name.endsWith(".class") || !name.startsWith(PACKAGE_PREFIX)) {
                    continue;
                }

                // Ok, we found something
                try (InputStream in = zip.getInputStream(entry)) {
                    ClassNode classNode = MappingsParser.loadClassStructure(in);
                    mappingClasses.add(classNode);
                }
            }
        }
    }

    return new Mappings(mappingClasses);
}

From source file:com.partagames.imageresizetool.SimpleImageResizeTool.java

/**
 * Extracts file name from full file path.
 *
 * @param filePath File path/*from w w  w.  j  a  va  2 s . c  om*/
 * @return File name
 */
private static String extractFileNameFromPath(String filePath) {
    final Path p = Paths.get(filePath);
    return p.getFileName().toString();
}

From source file:net.certiv.antlr.project.util.Utils.java

/**
 * Move all files from the source directory to the destination directory.
 * /*from w  ww . ja  v a 2 s. c  om*/
 * @param source
 *            the source directory
 * @param dest
 *            the destination directory
 * @return
 * @throws IOException
 */
public static boolean moveAllFiles(File source, File dest) throws IOException {
    if (source == null || dest == null)
        throw new IllegalArgumentException("Directory cannot be null");
    if (!source.exists() || !source.isDirectory())
        throw new IOException("Source directory must exist: " + source.getCanonicalPath());

    dest.mkdirs();
    if (!dest.exists() || !dest.isDirectory())
        throw new IOException("Destination directory must exist: " + dest.getCanonicalPath());

    Path srcDir = source.toPath();
    Path dstDir = dest.toPath();
    DirectoryStream<Path> ds = Files.newDirectoryStream(srcDir);
    int tot = 0;
    for (Path src : ds) {
        Files.copy(src, dstDir.resolve(src.getFileName()), REPLACE_EXISTING);
        tot++;
    }
    Log.info(Utils.class, "Moved " + tot + " files");
    return false;
}

From source file:test.TestJavaService.java

/**
 * Make the special JSON encoding with both a schema and some number of CSV files must be provided
 * TODO at present there is no way to send "format" or "delimiter" members
 * @param schemaString a String containing the JSON schema
 * @param files the list of file names which are to be read to obtain CSV and whose names are to be decomposed to
 *   form type (table) names//from  w  ww  .  ja  va  2 s  .  c  o  m
 * @return the JSON encoding to send
 * @throws IOException 
 */
private static String makeSpecialJson(String schemaString, List<String> files) throws IOException {
    JsonObject result = new JsonObject();
    JsonObject schema = new JsonParser().parse(schemaString).getAsJsonObject();
    result.add("schema", schema);
    JsonObject data = new JsonObject();
    result.add("data", data);
    for (String file : files) {
        Path path = Paths.get(file);
        String csv = new String(Files.readAllBytes(path));
        String table = path.getFileName().toString();
        if (table.endsWith(".csv"))
            table = table.substring(0, table.length() - 4);
        data.add(table, new JsonPrimitive(csv));
    }
    return result.toString();
}

From source file:com.liferay.sync.engine.util.FileUtil.java

public static boolean isIgnoredFilePath(Path filePath) throws Exception {
    String fileName = String.valueOf(filePath.getFileName());

    if (_syncFileIgnoreNames.contains(fileName)
            || (PropsValues.SYNC_FILE_IGNORE_HIDDEN && Files.isHidden(filePath))
            || Files.isSymbolicLink(filePath) || fileName.endsWith(".lnk")) {

        return true;
    }//from   ww  w.  j  a  v  a 2 s  .c om

    return false;
}

From source file:ee.ria.xroad.confproxy.util.ConfProxyHelper.java

/**
 * Gets the list of subdirectory names in the given directory path.
 * @param dir path to the directory//ww  w. j  av  a  2s  .c o m
 * @return list of subdirectory names
 * @throws IOException if opening the directory fails
 */
private static List<String> subDirectoryNames(final Path dir) throws IOException {
    List<String> subdirs = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, Files::isDirectory)) {
        for (Path subDir : stream) {
            String conf = subDir.getFileName().toString();
            subdirs.add(conf);
        }
        return subdirs;
    }
}