Example usage for java.nio.file Files exists

List of usage examples for java.nio.file Files exists

Introduction

In this page you can find the example usage for java.nio.file Files exists.

Prototype

public static boolean exists(Path path, LinkOption... options) 

Source Link

Document

Tests whether a file exists.

Usage

From source file:com.kamike.misc.FsUtils.java

public static void createDirectory(String dstPath) {

    Properties props = System.getProperties(); //    
    String osName = props.getProperty("os.name"); //???   
    Path newdir = FileSystems.getDefault().getPath(dstPath);

    boolean pathExists = Files.exists(newdir, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
    if (!pathExists) {
        Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx");
        FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
        try {/*from  ww w  .j av a  2s .  co m*/
            if (!osName.contains("Windows")) {
                Files.createDirectories(newdir, attr);
            } else {
                Files.createDirectories(newdir);
            }
        } catch (Exception e) {
            System.err.println(e);

        }
    }
}

From source file:com.bbva.kltt.apirest.core.util.parser.ParserUtil.java

/**
 * Read the file content//from  w ww.  j ava2s.c  o  m
 *
 * @param filePath with the file path
 * @return the file content
 * @throws APIRestGeneratorException with an occurred exception
 */
public static String readFileContent(final String filePath) throws APIRestGeneratorException {
    Path path = null;

    if (filePath.toLowerCase().startsWith(ConstantsInput.SO_PATH_STRING_PREFIX)) {
        path = Paths.get(URI.create(filePath));
    } else {
        path = Paths.get(filePath, new String[0]);
    }

    String fileContent = null;

    if (Files.exists(path, new LinkOption[0])) {
        try {
            fileContent = FileUtils.readFileToString(path.toFile(), "UTF-8");
        } catch (IOException ioException) {
            final String errorString = "IOException when reading the file: " + ioException;

            ParserUtil.LOGGER.error(errorString, ioException);
            throw new APIRestGeneratorException(errorString, ioException);
        }
    } else {
        fileContent = FilesUtility.loadFileContentFromClasspath(filePath);
    }

    return fileContent;
}

From source file:com.vns.pdf.impl.PdfDocument.java

private void setWorkingDir() throws IOException {
    ApplicationProperties.KEY.PdfDir.asString();
    workingDir = Paths.get(ApplicationProperties.KEY.PdfDir.asString());
    Files.createDirectories(workingDir, new FileAttribute[0]);
    pdfTempDir = Paths.get(ApplicationProperties.KEY.Workspace.asString(), "temp");
    if (!Files.exists(pdfTempDir, LinkOption.NOFOLLOW_LINKS)) {
        Files.createDirectories(pdfTempDir);
    }/*from   w  ww. j  av  a 2s . co  m*/
    ImageIO.setCacheDirectory(pdfTempDir.toFile());
    ImageIO.setUseCache(true);
}

From source file:it.reexon.lib.files.FileUtils.java

/**
 * Deletes a file. /*from   ww w.  ja  va  2 s  .com*/
 * 
 * @param file the path to the file 
 * @return boolean 
 * @throws IOException if an I/O error occurs
 * @throws IllegalArgumentException if file is null
 */
public static boolean deleteFile(Path file) throws IOException {
    if ((file == null))
        throw new IllegalArgumentException("file cannot be null");
    try {
        if (file.toFile().canWrite()) {
            Files.delete(file);
        }
        return !Files.exists(file, LinkOption.NOFOLLOW_LINKS);
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("An IO exception occured while deleting file '" + file + "' with error:"
                + e.getLocalizedMessage());
    }
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<Path> getZipArchive(boolean cached) {
    try {/*  w w w . ja va  2s. c o  m*/
        Path cachedFilePath = cachedArchivePath();
        Path parentDirectoryPath = cachedFilePath.getParent();

        // create the parent directory it doesn't already exist
        if (Files.notExists(parentDirectoryPath, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(parentDirectoryPath);
        }

        // if cached file already exist - return it, no download necessary
        if (cached && Files.exists(cachedFilePath, LinkOption.NOFOLLOW_LINKS)) {
            return Optional.of(cachedFilePath.toAbsolutePath());
        }

        // otherwise, download the file
        URL url = new URL(PROTEINS_URL);
        Files.copy(url.openStream(), cachedFilePath, StandardCopyOption.REPLACE_EXISTING);
        return Optional.of(cachedFilePath.toAbsolutePath());

    } catch (MalformedURLException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }

    return Optional.empty();
}

From source file:edu.ehu.galan.lite.model.Document.java

/**
 * Save results in a plain text file following the pattern.... topic + \tab +
 * Source_knowledge_id+ \tab + Source_knowledge_title
 *
 * @param pFolder - where you want to save the results
 * @param pDoc/*from   w ww.  j  a v  a  2  s  .  com*/
 */
public static void saveResults(String pFolder, Document pDoc) {
    if (Files.isDirectory(Paths.get(pFolder), LinkOption.NOFOLLOW_LINKS)) {
        PrintWriter printWriter = null;
        try {
            printWriter = new PrintWriter(new File(pFolder + "/" + pDoc.name), "UTF-8");

            for (Topic topic : pDoc.topicList) {
                printWriter.println(topic.getTopic() + "\t" + topic.getId() + "\t" + topic.getSourceTitle());
            }
            printWriter.close();
        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            logger.error("error printing the file: " + pFolder, ex);
        }
        logger.info(pDoc.path + "  Saved... ");
    } else if (Files.exists(Paths.get(pFolder), LinkOption.NOFOLLOW_LINKS)) {
        logger.error("The folder exists but it isn't a directory...maybe a file?");
    } else {
        logger.warn("The directory doesn't exist... will be created");
        try {
            FileUtils.forceMkdir(new File(pFolder));
            PrintWriter printWriter = null;
            printWriter = new PrintWriter(new File(pFolder + "/" + pDoc.name), "UTF-8");
            for (Topic topic : pDoc.topicList) {
                printWriter.println(topic.getTopic() + "\t" + topic.getId() + "\t" + topic.getSourceTitle());
            }
            printWriter.close();
            logger.info(pDoc.path + "  Saved... ");
        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            logger.error("error printing the file: " + pFolder, ex);
        } catch (IOException ex) {
            logger.error("Error while creating directories in or printing the file: " + pFolder, ex);
        }
    }

}

From source file:au.edu.uq.cmm.paul.queue.AbstractQueueFileManager.java

@Override
public final File renameGrabbedDatafile(File file) throws QueueFileException {
    String extension = FilenameUtils.getExtension(file.toString());
    if (!extension.isEmpty()) {
        extension = "." + extension;
    }//from w  w  w .j av a  2s. co  m
    for (int i = 0; i < RETRY; i++) {
        File newFile = generateUniqueFile(extension, false);
        if (!file.renameTo(newFile)) {
            if (!Files.exists(newFile.toPath(), LinkOption.NOFOLLOW_LINKS)) {
                throw new QueueFileException("Unable to rename file or symlink " + file + " to " + newFile);
            }
        } else {
            return newFile;
        }
    }
    throw new QueueFileException(RETRY + " attempts to rename file / symlink failed!");
}