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:Main.java

public static void main(String[] args) {

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

    boolean path_exists = Files.exists(path, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
    System.out.println("Exists? " + path_exists);
}

From source file:Main.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("exists (Do not follow links): " + Files.exists(firstPath, LinkOption.NOFOLLOW_LINKS));

}

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(/*from  w  w w  .  j a  v  a2 s  . co  m*/
            "notExists (Do not follow links): " + Files.notExists(firstPath, LinkOption.NOFOLLOW_LINKS));
    System.out.println("notExists: " + Files.notExists(firstPath));

}

From source file:com.github.houbin217jz.thumbnail.Thumbnail.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("s", "src", true,
            "????????????");
    options.addOption("d", "dst", true, "");
    options.addOption("r", "ratio", true, "/??, 30%???0.3????????");
    options.addOption("w", "width", true, "(px)");
    options.addOption("h", "height", true, "?(px)");
    options.addOption("R", "recursive", false, "???????");

    HelpFormatter formatter = new HelpFormatter();
    String formatstr = "java -jar thumbnail.jar " + "[-s/--src <path>] " + "[-d/--dst <path>] "
            + "[-r/--ratio double] " + "[-w/--width integer] " + "[-h/--height integer] " + "[-R/--recursive] ";

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;// w  ww.  ja va 2  s .com
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e1) {
        formatter.printHelp(formatstr, options);
        return;
    }

    final Path srcDir, dstDir;
    final Integer width, height;
    final Double ratio;

    //
    if (cmd.hasOption("s")) {
        srcDir = Paths.get(cmd.getOptionValue("s")).toAbsolutePath();
    } else {
        srcDir = Paths.get("").toAbsolutePath(); //??
    }

    //
    if (cmd.hasOption("d")) {
        dstDir = Paths.get(cmd.getOptionValue("d")).toAbsolutePath();
    } else {
        formatter.printHelp(formatstr, options);
        return;
    }

    if (!Files.exists(srcDir, LinkOption.NOFOLLOW_LINKS)
            || !Files.isDirectory(srcDir, LinkOption.NOFOLLOW_LINKS)) {
        System.out.println("[" + srcDir.toAbsolutePath() + "]??????");
        return;
    }

    if (Files.exists(dstDir, LinkOption.NOFOLLOW_LINKS)) {
        if (!Files.isDirectory(dstDir, LinkOption.NOFOLLOW_LINKS)) {
            //????????
            System.out.println("????????");
            return;
        }
    } else {
        //????????
        try {
            Files.createDirectories(dstDir);
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    //??
    if (cmd.hasOption("w") && cmd.hasOption("h")) {
        try {
            width = Integer.valueOf(cmd.getOptionValue("width"));
            height = Integer.valueOf(cmd.getOptionValue("height"));
        } catch (NumberFormatException e) {
            System.out.println("??????");
            return;
        }
    } else {
        width = null;
        height = null;
    }

    //?
    if (cmd.hasOption("r")) {
        try {
            ratio = Double.valueOf(cmd.getOptionValue("r"));
        } catch (NumberFormatException e) {
            System.out.println("?????");
            return;
        }
    } else {
        ratio = null;
    }

    if (width != null && ratio != null) {
        System.out.println("??????????????");
        return;
    }

    if (width == null && ratio == null) {
        System.out.println("????????????");
        return;
    }

    //
    int maxDepth = 1;
    if (cmd.hasOption("R")) {
        maxDepth = Integer.MAX_VALUE;
    }

    try {
        //Java 7 ??@see http://docs.oracle.com/javase/jp/7/api/java/nio/file/Files.html
        Files.walkFileTree(srcDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), maxDepth,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                            throws IOException {

                        //???&???
                        String filename = path.getFileName().toString().toLowerCase();

                        if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                            //Jpeg??

                            /*
                             * relative??:
                             * rootPath: /a/b/c/d
                             * filePath: /a/b/c/d/e/f.jpg
                             * rootPath.relativize(filePath) = e/f.jpg
                             */

                            /*
                             * resolve??
                             * rootPath: /a/b/c/output
                             * relativePath: e/f.jpg
                             * rootPath.resolve(relativePath) = /a/b/c/output/e/f.jpg
                             */

                            Path dst = dstDir.resolve(srcDir.relativize(path));

                            if (!Files.exists(dst.getParent(), LinkOption.NOFOLLOW_LINKS)) {
                                Files.createDirectories(dst.getParent());
                            }
                            doResize(path.toFile(), dst.toFile(), width, height, ratio);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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:de.teamgrit.grit.report.PdfConcatenator.java

/**
 * Concatinates pdfs generated {@link TexGenerator}.
 *
 * @param folderWithPdfs//from   w  w  w  .j  av a  2s.  co  m
 *            the folder with pdfs
 * @param outPath
 *            the out path
 * @param exerciseName
 *            the context
 * @param studentsWithoutSubmissions
 *            list of students who did not submit any solution
 * @return the path to the created PDF
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
protected static Path concatPDFS(Path folderWithPdfs, Path outPath, String exerciseName,
        List<Student> studentsWithoutSubmissions) throws IOException {

    if ((folderWithPdfs == null) || !Files.isDirectory(folderWithPdfs)) {
        throw new IOException("The Path doesn't point to a Folder");
    }

    File file = new File(outPath.toFile(), "report.tex");

    if (Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS)) {
        Files.delete(file.toPath());
    }
    file.createNewFile();

    writePreamble(file, exerciseName);
    writeMissingStudents(file, studentsWithoutSubmissions);
    writeFiles(file, folderWithPdfs);
    writeClosing(file);

    PdfCreator.createPdfFromPath(file.toPath(), outPath);

    return file.toPath();

}

From source file:de.teamgrit.grit.report.PlainGenerator.java

/**
 * This method creates a plain-text file from a SubmissionObj instance.
 * // w w w  . j a v a  2  s  .com
 * @param submission
 *            A SubmissionObj containing the information that the content
 *            gets generated from.
 * @param outdir
 *            the output directory
 * @param courseName
 *            the name of the Course
 * @param exerciseName
 *            the name of the exercise
 * @return The Path to the created plain-text file.
 * @throws IOException
 *             If something goes wrong when writing.
 */
public static Path generatePlain(final Submission submission, final Path outdir, String courseName,
        String exerciseName) throws IOException {
    final File location = outdir.toFile();

    File outputFile = new File(location, submission.getStudent().getName() + ".report.txt");
    if (Files.exists(outputFile.toPath(), LinkOption.NOFOLLOW_LINKS)) {
        Files.delete(outputFile.toPath());
    }
    outputFile.createNewFile();

    writeHeader(outputFile, submission, courseName, exerciseName);
    writeOverview(outputFile, submission);
    writeTestResult(outputFile, submission);

    // if there are compile errors, put these in the text file instead of
    // JUnit Test result
    CheckingResult checkingResult = submission.getCheckingResult();
    if (checkingResult.getCompilerOutput().compilerStreamBroken()) {
        writeCompilerErrors(outputFile, submission);
    } else {
        TestOutput testResults = checkingResult.getTestResults();
        if ((testResults.getPassedTestCount() < testResults.getTestCount()) && testResults.getDidTest()) {
            writeFailedTests(outputFile, submission);
        }
    }

    writeCompilerOutput(outputFile, submission);

    return outputFile.toPath();
}

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

public static void createDir(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  w ww.  j  a v a2s .c  o 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.web.Utilities.java

/**
 * Read the file content//  w ww  .ja v a 2s.co m
 * @param filePath with the file path
 * @return the file content as byte array
 * @throws APIRestGeneratorException with an occurred exception
 */
public static byte[] 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]);
    }

    byte[] fileContent = null;

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

            Utilities.LOGGER.error(errorString, ioException);
            throw new APIRestGeneratorException(errorString, ioException);
        }
    }

    return fileContent;
}

From source file:org.v2020.service.ie.test.VnaImportTest.java

@Test
public void testVna() throws Exception {
    byte[] vnaFileData = FileSystem.readByteArrayFromClasspath(RISK_CATALOG_FILE_NAME);
    assertNotNull("File data is null, file name: " + RISK_CATALOG_FILE_NAME, vnaFileData);
    Vna vna = new Vna(vnaFileData);
    byte[] xmlFiledata = vna.getXmlFileData();
    assertNotNull("Xml file data is null.", xmlFiledata);
    SyncRequest syncRequest = vna.getXml();
    assertNotNull("SyncRequest is null.", syncRequest);
    SyncData syncData = syncRequest.getSyncData();
    assertNotNull("SyncData is null.", syncData);
    List<SyncObject> syncObjects = syncData.getSyncObject();
    assertNotNull("SyncObject list is null.", syncObjects);
    assertFalse("SyncObject list is empty.", syncObjects.isEmpty());
    SyncObject syncObject = syncObjects.get(0);
    assertNotNull("SyncObject is null.", syncObject);
    vna.clear();//from  w w w.  j a  v a2  s  .  co m
    assertFalse("Temp folder still exists: " + vna.getTempFileName(),
            Files.exists(Paths.get(vna.getTempFileName()), LinkOption.NOFOLLOW_LINKS));
}