List of usage examples for java.nio.file Files isDirectory
public static boolean isDirectory(Path path, LinkOption... options)
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.isDirectory(path, LinkOption.NOFOLLOW_LINKS)); }
From source file:Main.java
public static void main(String[] args) { Path path = Paths.get("C:/tutorial/Java/JavaFX"); DirectoryStream.Filter<Path> dir_filter = new DirectoryStream.Filter<Path>() { public boolean accept(Path path) throws IOException { return (Files.isDirectory(path, NOFOLLOW_LINKS)); }// w w w. j av a2s .com }; try (DirectoryStream<Path> ds = Files.newDirectoryStream(path, dir_filter)) { for (Path file : ds) { System.out.println(file.getFileName()); } } catch (IOException e) { System.err.println(e); } }
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;//from ww w . ja v a 2s .co m 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:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java
private List<Path> listArchiveFiles(Path underHere) { List res = new ArrayList<>(); try {/* w w w .j a v a 2 s.c o m*/ Files.newDirectoryStream(underHere).forEach((p) -> { if (Files.isRegularFile(p, LinkOption.NOFOLLOW_LINKS)) { res.add(p); } else if (Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS)) { res.addAll(listArchiveFiles(p)); } }); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } return res; }
From source file:com.jvms.i18neditor.Editor.java
public void importResources(Path dir) { if (!closeCurrentSession()) { return;/* w w w.j a v a 2 s . co m*/ } if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) { reset(); resourcesDir = dir; } else { showError(MessageBundle.get("resources.open.error.multiple")); return; } try { Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path)).forEach(path -> { try { Resource resource = Resources.read(path); setupResource(resource); } catch (Exception e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.single", path.toString())); } }); List<String> recentDirs = settings.getListProperty("history"); recentDirs.remove(resourcesDir); recentDirs.add(resourcesDir.toString()); if (recentDirs.size() > 5) { recentDirs.remove(0); } settings.setProperty("history", recentDirs); editorMenu.setRecentItems(Lists.reverse(recentDirs)); Map<String, String> keys = Maps.newTreeMap(); resources.forEach(resource -> keys.putAll(resource.getTranslations())); List<String> keyList = Lists.newArrayList(keys.keySet()); translationTree.setModel(new TranslationTreeModel(keyList)); updateUI(); } catch (IOException e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.multiple")); } }
From source file:desktopsearch.WatchDir.java
/** * Process all events for keys queued to the watcher *//*from w w w . j a va2 s . c om*/ void processEvents() { for (;;) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException x) { return; } Path dir = keys.get(key); if (dir == null) { System.err.println("WatchKey not recognized!!"); continue; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // TBD - provide example of how OVERFLOW event is handled if (kind == OVERFLOW) { continue; } // Context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // if directory is created, and watching recursively, then // register it and its sub-directories if (recursive && (kind == ENTRY_CREATE)) { try { if (Files.isDirectory(child, NOFOLLOW_LINKS)) { registerAll(child); } } catch (Exception x) { // ignore to keep sample readbale } } // print out event //System.out.format("%s: %s\n", event.kind().name(), child); try { UpdateDB(event.kind().name(), child); } catch (Exception e) { e.printStackTrace(); } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { keys.remove(key); // all directories are inaccessible if (keys.isEmpty()) { break; } } } }
From source file:com.ejie.uda.jsonI18nEditor.Editor.java
public void importResources(Path dir) { Stream<Path> filter; try {// ww w. j a v a 2 s .com if (!closeCurrentSession()) { return; } if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) { reset(); resourcesDir = dir; filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path)); } else { reset(); // Se ha arrastrado un fichero de 18n individual, se debe de obtener los recursos relacionados con el bundle al que pertenece. Pattern.matches(BUNDLE_REGEX, dir.getFileName().toString()); Pattern regex = Pattern.compile(BUNDLE_REGEX); resourcesDir = dir.getParent(); inputFile = dir; Matcher regexMatcher = regex.matcher(dir.getFileName().toString()); if (regexMatcher.find()) { this.bundle = regexMatcher.group(1); filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path, this.bundle)); } else { showError(MessageBundle.get("resources.open.error.multiple")); return; } // Pattern.matches("BUNDLE_REGEX", dir.getFileName().toString()); // showError(MessageBundle.get("resources.open.error.multiple")); // return; } filter.forEach(path -> { try { Resource resource = Resources.read(path); setupResource(resource); } catch (Exception e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.single", path.toString())); } }); List<String> recentDirs = settings.getListProperty("history"); recentDirs.remove(dir); recentDirs.add(dir.toString()); if (recentDirs.size() > 5) { recentDirs.remove(0); } settings.setProperty("history", recentDirs); editorMenu.setRecentItems(Lists.reverse(recentDirs)); Map<String, String> keys = Maps.newTreeMap(); resources.forEach(resource -> keys.putAll(resource.getTranslations())); // resources.forEach(resource -> { // // // // }); List<String> keyList = Lists.newArrayList(keys.keySet()); translationTree.setModel(new TranslationTreeModel(keyList)); updateUI(); // for (String key : keyList) { // boolean anyEmpty = false; // // for (Resource resource : resources) { // if (StringUtils.isBlank(resource.getTranslation(key))){ // anyEmpty = true; // } // } // // TranslationTreeModel model = (TranslationTreeModel) translationTree.getModel(); // TranslationTreeNode node = model.getNodeByKey(key); // // node // } // keyList.stream().filter(key -> { // // resources.stream().filter(resource -> { // return StringUtils.isNotBlank(resource.getTranslation(key)); // }); // return true; // }); } catch (IOException e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.multiple")); } }
From source file:com.phoenixnap.oss.ramlapisync.plugin.SpringMvcRamlApiSyncMojo.java
public void execute() throws MojoExecutionException, MojoFailureException { long startTime = System.currentTimeMillis(); if (project.getPackaging().equals("pom")) { this.getLog().info("Skipping [pom] project: " + project.getName()); } else if (project.getPackaging().equals("maven-plugin")) { this.getLog().info("Skipping [maven-plugin] project: " + project.getName()); } else if (!Files.isDirectory(Paths.get(project.getBuild().getSourceDirectory()), LinkOption.NOFOLLOW_LINKS)) { this.getLog().info("Skipping project with missing src folder: " + project.getName()); } else {//w ww .ja v a2 s.com try { generateRaml(); } catch (IOException e) { ClassLoaderUtils.restoreOriginalClassLoader(); throw new MojoExecutionException(e, "Unexpected exception while executing Raml Sync Plugin.", e.toString()); } } this.getLog().info("Raml Generation Complete in:" + (System.currentTimeMillis() - startTime) + "ms"); }
From source file:com.drunkendev.io.recurse.tests.RecursionTest.java
/** * Answer provided by Brett Ryan.//w ww . j a v a2 s . c om * * This test uses Java-8's java {@link java.util.stream.Stream Stream API} * by {@link Files#walk}. * * This is the sequential version. * * @see <a href="http://stackoverflow.com/a/24006711/140037">Stack-Overflow answer by Brett Ryan</a> */ // @Test public void testJava8StreamSequential() { System.out.println("\nTEST: Java 8 Stream Sequential"); time(() -> { try { Map<Integer, Long> stats = Files.walk(startPath).sequential().collect( groupingBy(n -> Files.isDirectory(n, LinkOption.NOFOLLOW_LINKS) ? 1 : 2, counting())); System.out.format("Files: %d, dirs: %d. ", stats.get(2), stats.get(1)); } catch (IOException ex) { fail(ex.getMessage()); } }); }