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.ejisto.util.IOUtils.java

public static Collection<String> findAllClassesInJarFile(File jarFile) throws IOException {
    final List<String> ret = new ArrayList<>();
    Map<String, String> env = new HashMap<>();
    env.put("create", "false");
    try (FileSystem targetFs = FileSystems.newFileSystem(URI.create("jar:file:" + jarFile.getAbsolutePath()),
            env)) {/*from   w  w  w .  j a  va2 s .  com*/
        final Path root = targetFs.getPath("/");
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String ext = ".class";
                if (attrs.isRegularFile() && file.getFileName().toString().endsWith(ext)) {
                    String path = root.relativize(file).toString();
                    ret.add(translatePath(path.substring(0, path.length() - ext.length()), "/"));
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
    return ret;
}

From source file:ch.bender.evacuate.Helper.java

/**
 * Appends a number suffix to the name of the Path object. If the flag BeforeExtension is
 * <code>true</code>, the number is appended before the last dot in the file name.
 * <p>//  www  .  ja  v  a  2  s .  c  o m
 * See examples in {@link #appendNumberSuffix(Path, int)}
 * <p>
 * 
 * @param aPath
 *        the path whose name should be suffixed
 * @param aNumber
 *        the number to suffix
 * @param aBeforeExtension 
 *        <code>true</code>: the extension stays the last part of the filename.
 * @return the new path
 */
public static Path appendNumberSuffix(Path aPath, int aNumber, boolean aBeforeExtension) {
    DecimalFormat df = new DecimalFormat("00");
    String suffix = "_" + df.format(aNumber);

    String parent = aPath.getParent() == null ? "" : aPath.getParent().toString();
    String extension = "";
    String name = aPath.getFileName().toString();

    if (aBeforeExtension) {
        extension = FilenameUtils.getExtension(name);

        if (extension.length() > 0) {
            extension = "." + extension;
        }
        name = FilenameUtils.getBaseName(name);
    }

    return Paths.get(parent, name + suffix + extension);
}

From source file:com.romeikat.datamessie.core.base.util.FileUtil.java

private static Path getNonExisting(Path path) {
    // Return path, if it does not exist
    if (!Files.exists(path)) {
        return path;
    }//w ww . j av a 2  s  . c o m
    // Determine name and extension
    final String name = path.getFileName().toString();
    final int fileTypeIndex = name.lastIndexOf(".");
    String nameWithoutExtension;
    String extension;
    if (fileTypeIndex == -1) {
        nameWithoutExtension = name;
        extension = "";
    } else {
        nameWithoutExtension = name.substring(0, fileTypeIndex);
        extension = name.substring(fileTypeIndex);
    }
    // Determine number
    final int underscoreIndex = name.lastIndexOf("_");
    String nameWithoutExtensionWithoutNumber;
    Integer nextNumber = 1;
    if (underscoreIndex == -1) {
        nameWithoutExtensionWithoutNumber = nameWithoutExtension;
    } else {
        nameWithoutExtensionWithoutNumber = nameWithoutExtension.substring(0, underscoreIndex);
        final String numberString = name.substring(underscoreIndex + 1);
        try {
            nextNumber = Integer.parseInt(numberString) + 1;
        } catch (final NumberFormatException e) {
        }
    }
    // Determine next candidate
    String nextName;
    while (true) {
        nextName = nameWithoutExtensionWithoutNumber + "_" + nextNumber++ + extension;
        path = Paths.get(path.getParent().toString(), nextName);
        if (!Files.exists(path)) {
            return path;
        }
    }
}

From source file:de.ingrid.interfaces.csw.tools.FileUtils.java

/**
 * Delete a file or directory specified by a {@link Path}. This method uses
 * the new {@link Files} API and allows to specify a regular expression to
 * remove only files that match that expression.
 * /*from  w w w  .j a v  a2  s  .c  o m*/
 * @param path
 * @param pattern
 * @throws IOException
 */
public static void deleteRecursive(Path path, final String pattern) throws IOException {

    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern);

    if (!Files.exists(path))
        return;

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            // try to delete the file anyway, even if its attributes
            // could not be read, since delete-only access is
            // theoretically possible
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc == null) {
                if (matcher.matches(dir.getFileName())) {
                    if (dir.toFile().list().length > 0) {
                        // remove even if not empty
                        FileUtils.deleteRecursive(dir);
                    } else {
                        Files.delete(dir);
                    }
                }
                return FileVisitResult.CONTINUE;
            } else {
                // directory iteration failed; propagate exception
                throw exc;
            }
        }

    });
}

From source file:org.apache.taverna.robundle.manifest.Manifest.java

protected static Path withSlash(Path dir) {
    if (dir == null)
        return null;
    if (isDirectory(dir)) {
        Path fname = dir.getFileName();
        if (fname == null)
            return dir;
        String fnameStr = fname.toString();
        if (fnameStr.endsWith("/"))
            return dir;
        return dir.resolveSibling(fnameStr + "/");
    }//from w w  w.j a va 2  s  .co m
    return dir;
}

From source file:com.nwn.NwnFileHandler.java

/**
 * Extracts contents of given file to provided directory
 * @param file File to extract//from   w w w .  j  ava  2  s .c  om
 * @param dest Location to extract to
 * @return True if extract success, False if extract failed
 */
public static boolean extractFile(Path file, Path dest) {
    if (getFileExtension(file.toString()).equals("zip")) {
        try {
            ZipFile zipFile = new ZipFile(file.toString());
            if (zipFile.isEncrypted()) {
                System.out.println(
                        "Cannot extract from " + file.getFileName().toString() + ": Password required.");
                return false;
            } else {
                zipFile.extractAll(dest.toString());
            }
        } catch (ZipException ex) {
            ex.printStackTrace();
            return false;
        }
    } else if (getFileExtension(file.toString()).equals("rar")) {//todo: finish
        Archive a = null;
        try {
            a = new Archive(new FileVolumeManager(file.toFile()));
        } catch (RarException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (a != null) {
            a.getMainHeader().print();
            FileHeader fh = a.nextFileHeader();
            while (fh != null) {
                try {
                    File out = new File(dest.toString() + File.separator + fh.getFileNameString().trim());
                    System.out.println(out.getAbsolutePath());
                    FileOutputStream os = new FileOutputStream(out);
                    a.extractFile(fh, os);
                    os.close();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (RarException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                fh = a.nextFileHeader();
            }
        }
    }
    return true;
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static boolean pathEndsWith(java.nio.file.Path p, String end) {
    return p.getFileName().toString().endsWith(end);
}

From source file:org.apache.lens.regression.util.Util.java

public static void changeConfig(HashMap<String, String> map, String remotePath) throws Exception {

    Path p = Paths.get(remotePath);
    String fileName = p.getFileName().toString();
    backupFile = localFilePath + "backup-" + fileName;
    localFile = localFilePath + fileName;
    log.info("Copying " + remotePath + " to " + localFile);
    remoteFile("get", remotePath, localFile);
    Files.copy(new File(localFile).toPath(), new File(backupFile).toPath(), REPLACE_EXISTING);

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = docBuilder.parse(new FileInputStream(localFile));
    doc.normalize();//w  w  w .ja v  a2s . co  m

    NodeList rootNodes = doc.getElementsByTagName("configuration");
    Node root = rootNodes.item(0);
    Element rootElement = (Element) root;
    NodeList property = rootElement.getElementsByTagName("property");

    for (int i = 0; i < property.getLength(); i++) { //Deleting redundant properties from the document
        Node prop = property.item(i);
        Element propElement = (Element) prop;
        Node propChild = propElement.getElementsByTagName("name").item(0);

        Element nameElement = (Element) propChild;
        if (map.containsKey(nameElement.getTextContent())) {
            rootElement.removeChild(prop);
            i--;
        }
    }

    Iterator<Entry<String, String>> ab = map.entrySet().iterator();
    while (ab.hasNext()) {
        Entry<String, String> entry = ab.next();
        String propertyName = entry.getKey();
        String propertyValue = entry.getValue();
        System.out.println(propertyName + " " + propertyValue + "\n");
        Node newNode = doc.createElement("property");
        rootElement.appendChild(newNode);
        Node newName = doc.createElement("name");
        Element newNodeElement = (Element) newNode;

        newName.setTextContent(propertyName);
        newNodeElement.appendChild(newName);

        Node newValue = doc.createElement("value");
        newValue.setTextContent(propertyValue);
        newNodeElement.appendChild(newValue);
    }
    prettyPrint(doc);
    remoteFile("put", remotePath, localFile);
}

From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java

public static boolean pathStartsWith(java.nio.file.Path p, String start) {
    return p.getFileName().toString().startsWith(start);
}

From source file:edu.cmu.tetrad.cli.search.FgsDiscrete.java

private static void writeOutGraphML(Graph graph, Path outputFile) {
    if (graph == null) {
        return;// w  w w .  j  a v a 2 s  .  c  om
    }

    try (PrintStream graphWriter = new PrintStream(
            new BufferedOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE)))) {
        String fileName = outputFile.getFileName().toString();

        String msg = String.format("Writing out GraphML file '%s'.", fileName);
        System.out.printf("%s: %s%n", DateTime.printNow(), msg);
        LOGGER.info(msg);
        XmlPrint.printPretty(GraphmlSerializer.serialize(graph, outputPrefix), graphWriter);
        msg = String.format("Finished writing out GraphML file '%s'.", fileName);
        System.out.printf("%s: %s%n", DateTime.printNow(), msg);
        LOGGER.info(msg);
    } catch (Throwable throwable) {
        String errMsg = String.format("Failed when writting out GraphML file '%s'.",
                outputFile.getFileName().toString());
        System.err.println(errMsg);
        LOGGER.error(errMsg, throwable);
    }
}