Example usage for java.nio.file Files notExists

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

Introduction

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

Prototype

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

Source Link

Document

Tests whether the file located by this path does not exist.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path path = FileSystems.getDefault().getPath("/home/docs/users.txt");
    System.out.println(Files.notExists(path, LinkOption.NOFOLLOW_LINKS));
}

From source file:Main.java

public static void main(String[] args) {

    Path path = FileSystems.getDefault().getPath("C:/tutorial/Java/JavaFX", "Demo.txt");

    boolean path_notexists = Files.notExists(path, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });

    System.out.println("Not exists? " + path_notexists);
}

From source file:Test.java

public static void main(String[] args) throws Exception {
    Path firstPath = Paths.get("/home/music/users.txt");
    Path secondPath = Paths.get("/docs/status.txt");
    System.out.println("From firstPath to secondPath: " + firstPath.relativize(secondPath));
    System.out.println("From secondPath to firstPath: " + secondPath.relativize(firstPath));
    System.out.println("exists (Do not follow links): " + Files.exists(firstPath, LinkOption.NOFOLLOW_LINKS));
    System.out.println("exists: " + Files.exists(firstPath));
    System.out.println(/*  w ww . j  av a2 s.c om*/
            "notExists (Do not follow links): " + Files.notExists(firstPath, LinkOption.NOFOLLOW_LINKS));
    System.out.println("notExists: " + Files.notExists(firstPath));

}

From source file:Test.java

private static void displayFileAttributes(Path path) throws Exception {
    String format = "Exists: %s %n" + "notExists: %s %n" + "Directory: %s %n" + "Regular: %s %n"
            + "Executable: %s %n" + "Readable: %s %n" + "Writable: %s %n" + "Hidden: %s %n" + "Symbolic: %s %n"
            + "Last Modified Date: %s %n" + "Size: %s %n";

    System.out.printf(format, Files.exists(path, LinkOption.NOFOLLOW_LINKS),
            Files.notExists(path, LinkOption.NOFOLLOW_LINKS),
            Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS),
            Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS), Files.isExecutable(path),
            Files.isReadable(path), Files.isWritable(path), Files.isHidden(path), Files.isSymbolicLink(path),
            Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS), Files.size(path));
}

From source file:pl.p.lodz.ftims.server.logic.ChallengeServiceTest.java

@BeforeClass
public static void createImgDir() throws IOException {
    if (Files.notExists(Paths.get(PHOTOS_DIR), LinkOption.NOFOLLOW_LINKS)) {
        Files.createDirectory(Paths.get(PHOTOS_DIR));
    }//from  w  w  w .j a v  a  2  s  .c o m
}

From source file:com.jejking.hh.nord.corpus.DrucksachenHtmlFetcher.java

/**
* Schedules tasks to fetch all the specified URLs leaving a random duration between the 
* execution of each task. /*from  ww  w  .ja v  a2 s .co  m*/
* 
* @param urlsToFetch
* @param storageDirectory
*/
public void fetchUrls(final ImmutableList<URL> urlsToFetch, final Path storageDirectory) {

    Observable<Runnable> tasks = Observable.from(urlsToFetch).filter(new Func1<URL, Boolean>() {

        @Override
        public Boolean call(URL url) {
            String encodedUrl = fileNameFromUrl(url) + ".gz";
            Path filePath = storageDirectory.resolve(encodedUrl);
            // retain only URLs for which we have no record yet so as not to download them twice
            return Files.notExists(filePath, LinkOption.NOFOLLOW_LINKS);
        }

    }).map(new Func1<URL, Runnable>() {
        @Override
        public Runnable call(final URL url) {
            return new Runnable() {

                @Override
                public void run() {

                    try {
                        File target = storageDirectory.resolve(fileNameFromUrl(url) + ".gz").toFile();
                        try (GzipCompressorOutputStream outputStream = new GzipCompressorOutputStream(
                                new BufferedOutputStream(new FileOutputStream(target)))) {
                            Resources.copy(url, outputStream);
                            System.out.println("Copied " + url + " to " + target);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            };

        };
    });

    tasks.subscribe(new Action1<Runnable>() {

        Random random = new Random();
        long cumulativeDelayInSeconds = 0;
        int count = 0;

        @Override
        public void call(Runnable runnable) {
            count++;
            DrucksachenHtmlFetcher.this.scheduledExecutorService.schedule(runnable, cumulativeDelayInSeconds,
                    TimeUnit.SECONDS);
            // at least two seconds, at most 10
            cumulativeDelayInSeconds = cumulativeDelayInSeconds + 2 + random.nextInt(9);
            DrucksachenHtmlFetcher.this.totalDelayHolder[0] = cumulativeDelayInSeconds;
            DrucksachenHtmlFetcher.this.actualCount[0] = count;
        }

    });

    System.out.println("Scheduled " + actualCount[0] + " tasks");
    System.out.println("Estimated duration " + totalDelayHolder[0] + " seconds");

    try {
        this.scheduledExecutorService.shutdown();
        // + 60 to allow task to finish comfortably...
        boolean finishedOK = this.scheduledExecutorService.awaitTermination(this.totalDelayHolder[0] + 60,
                TimeUnit.SECONDS);
        if (finishedOK) {
            System.out.println("Finished all tasks. Scheduled executor service shutdown.");
        } else {
            System.out.println("Executor service shutdown, but not all tasks completed.");
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

}

From source file:org.fcrepo.indexer.persistence.BasePersistenceIndexer.java

/**
 * Return the path where a given record should be persisted.
 * @param id The record's URI//w  w w .  ja  v a  2s  .  c om
 * @return the path where a given record should be persisted
 * @throws IOException if IO exception occurred
**/
protected Path pathFor(final URI id) throws IOException {

    // strip the http protocol and replace column(:) in front of the port number
    String fullPath = id.toString().substring(id.toString().indexOf("//") + 2);
    fullPath = StringUtils.substringBefore(fullPath, "/").replace(":", "/") + "/"
            + StringUtils.substringAfter(fullPath, "/");
    // URL encode the id
    final String idPath = URLEncoder.encode(substringAfterLast(fullPath, "/"), "UTF-8");

    // URL encode and build the file path
    final String[] pathTokens = StringUtils.substringBeforeLast(fullPath, "/").split("/");
    final StringBuilder pathBuilder = new StringBuilder();
    for (final String token : pathTokens) {
        if (StringUtils.isNotBlank(token)) {
            pathBuilder.append(URLEncoder.encode(token, "UTF-8") + "/");
        }
    }

    fullPath = pathBuilder.substring(0, pathBuilder.length() - 1).toString();

    final Path dir = Paths.get(pathName, fullPath);
    if (Files.notExists(dir, LinkOption.NOFOLLOW_LINKS)) {
        Files.createDirectories(Paths.get(pathName, fullPath));
    }
    return Paths.get(dir.toString(), idPath + extension);
}

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

private Optional<AIMedArticle> get() {
    if (paper != null) {
        return Optional.of(paper);
    }//from   ww  w . j a  va 2 s  . c  o  m

    try {
        Optional<Path> xmlpath = getPaperPath();
        if (xmlpath.isPresent()) {
            Path destinationD = Paths.get(basedir, "AIMedOpenAccess", "XML");

            if (Files.notExists(destinationD, LinkOption.NOFOLLOW_LINKS)) {
                Files.createDirectory(destinationD);
            }

            Path extractTo = Paths.get(basedir, "AIMedOpenAccess", "XML",
                    xmlpath.get().getFileName().toString());

            Files.copy(xmlpath.get(), extractTo, StandardCopyOption.REPLACE_EXISTING);

            // specify the location and name of xml file to be read  
            File xmlFile = extractTo.toFile();
            String articleString = FileUtils.readFileToString(xmlFile).trim();
            paper = new AIMedArticle(articleString);

            return Optional.of(paper);
        }
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
        return Optional.empty();
    }

    return Optional.empty();
}

From source file:org.apache.pulsar.io.file.FileSourceConfig.java

public void validate() {
    if (StringUtils.isBlank(inputDirectory)) {
        throw new IllegalArgumentException("Required property not set.");
    } else if (Files.notExists(Paths.get(inputDirectory), LinkOption.NOFOLLOW_LINKS)) {
        throw new IllegalArgumentException("Specified input directory does not exist");
    } else if (!Files.isReadable(Paths.get(inputDirectory))) {
        throw new IllegalArgumentException("Specified input directory is not readable");
    } else if (Optional.ofNullable(keepFile).orElse(false) && !Files.isWritable(Paths.get(inputDirectory))) {
        throw new IllegalArgumentException("You have requested the consumed files to be deleted, but the "
                + "source directory is not writeable.");
    }// w w  w. jav a2  s .co m

    if (StringUtils.isNotBlank(fileFilter)) {
        try {
            Pattern.compile(fileFilter);
        } catch (final PatternSyntaxException psEx) {
            throw new IllegalArgumentException("Invalid Regex pattern provided for fileFilter");
        }
    }

    if (minimumFileAge != null && Math.signum(minimumFileAge) < 0) {
        throw new IllegalArgumentException("The property minimumFileAge must be non-negative");
    }

    if (maximumFileAge != null && Math.signum(maximumFileAge) < 0) {
        throw new IllegalArgumentException("The property maximumFileAge must be non-negative");
    }

    if (minimumSize != null && Math.signum(minimumSize) < 0) {
        throw new IllegalArgumentException("The property minimumSize must be non-negative");
    }

    if (maximumSize != null && Math.signum(maximumSize) < 0) {
        throw new IllegalArgumentException("The property maximumSize must be non-negative");
    }

    if (pollingInterval != null && pollingInterval <= 0) {
        throw new IllegalArgumentException("The property pollingInterval must be greater than zero");
    }

    if (numWorkers != null && numWorkers <= 0) {
        throw new IllegalArgumentException("The property numWorkers must be greater than zero");
    }
}

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

private PdfDocument(String pdfFileName) throws IOException {
    this.pdfFileName = pdfFileName;
    setWorkingDir();/*from   w  w  w .j  a v a2 s. com*/
    Path filePath = Paths.get(pdfFileName);
    PosixFileAttributes attrs = Files.getFileAttributeView(filePath, PosixFileAttributeView.class)
            .readAttributes();
    String textAreaFileName = filePath.getFileName().toString() + "_" + filePath.toAbsolutePath().hashCode()
            + "_" + attrs.size() + "_" + attrs.lastModifiedTime().toString().replace(":", "_") + ".xml";
    textAreaFilePath = Paths.get(workingDir.toAbsolutePath().toString(), textAreaFileName);
    pdfTextStripper = new CustomPDFTextStripper();
    document = PDDocument.load(new File(pdfFileName));
    pdfRenderer = new PDFRenderer(document);

    if (Files.notExists(textAreaFilePath, LinkOption.NOFOLLOW_LINKS)) {
        pdfTextStripper.setSortByPosition(false);
        pdfTextStripper.setStartPage(0);
        pdfTextStripper.setEndPage(document.getNumberOfPages());

        this.doc = new Doc(new ArrayList<>(), new ArrayList<>());
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            PDPage pdPage = document.getPage(i);
            PDRectangle box = pdPage.getMediaBox();
            this.doc.getPages().add(new Page(new ArrayList<>(), new ArrayList<>(), (int) box.getWidth(),
                    (int) box.getHeight()));
        }

        Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
        try {
            pdfTextStripper.writeText(document, dummy);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
        parseBookmarksAnnotation();
        createTextAreaFile();
        //document.save(pdfFileName + ".pdf");
    } else {
        loadTextAreaFile();
    }
}