/*
* Copyright 2009 jail
*
* This file is part of find.
*
* find is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* find is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with find. If not, see http://www.gnu.org/licenses/.
*/
package find;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
import java.util.*;
/**
*
* @author jail
* Sample code that finds files that match the specified glob pattern.
* For more information on what constitutes a glob pattern, see
* http://java.sun.com/docs/books/tutorial/essential/io/fileOps.html#glob
*
* The file or directories that match the pattern are printed to
* standard out. The number of matches is also printed.
*
* When executing this application, you must put the glob pattern
* in quotes, so the shell will not expand any wild cards:
* java Find . -name "*.{java,class}"
*
* You may to exclude an entire subtree from the search by using
* "-prune" flag:
* java Find . -name "*.{java,class}" -prune
*
* Also, you may to use "-L" option which follows symbolic links.
* If you do this, make sure you test for circular links in the
* visitFile method:
* java Find . -name "*.{java,class}" -L
* Fortunately, you may use all options as one expression:
* java Find . -name "*.{java,class}" -L -prune
*/
public class Find {
/**
* A {@code FileVisitor} that finds all files that match the
* specified pattern.
*/
public static class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
//Compares the glob pattern against the file or directory name.
void find(Path file) {
Path name = file.getName();
if (name != null && matcher.matches(name)) {
numMatches++;
System.out.println(file);
}
}
//Prints the total number of matches to standard out.
void done() {
System.out.println("Matched: " + numMatches);
}
//Invoke the pattern matching method on each file.
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
find(file);
return CONTINUE;
}
//Invoke the pattern matching method on each directory.
@Override
public FileVisitResult preVisitDirectory(Path dir) {
find(dir);
return CONTINUE;
}
//If there is some error accessing the file system, let the
//user know the precise error.
@Override
public FileVisitResult preVisitDirectoryFailed(Path dir, IOException exc) {
if (exc instanceof AccessDeniedException) {
System.err.println(dir + ": cannot access directory");
} else {
System.err.println(exc);
}
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println(exc);
return CONTINUE;
}
}
static void usage() {
System.err.println("java Find <path> -name \"<glob_pattern>\"" +
"[-L | -prune]");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
if (args.length < 3 || !args[1].equals("-name"))
usage();
int argi = args.length;
Path startingDir = Paths.get(args[0]);
String pattern = args[2];
boolean excEntire = false;
boolean followsSimbolic = false;
if ((argi > 3) && (args[3].equals("-prune") || args[3].equals("-L"))) {
String s = args[3];
if (s.equals("-prune")) {
excEntire = true;
} else
followsSimbolic = true;
} else if (argi > 3) usage();
if ((argi > 4) && (args[4].equals("-prune") || args[4].equals("-L"))) {
String s = args[4];
if (s.equals("-prune")) {
excEntire = true;
} else
followsSimbolic = true;
} else if (argi > 4) usage();
if (followsSimbolic) {
// follow links when searching files
EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, opts, Integer.MAX_VALUE, finder);
}
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
finder.done();
}
}
Поиск в директории.Как сделать?
я делаю програмку, одна из функций которой определить версию jre, установленные hot spots, директорию в которой установлена, архитектуру, и т.д.....
Нужно чтобы пользователь вводил директорию, в которой будет производится поиск уствновленной jre, и если будет найдено - выдадутся требуемые параметры.
Как можно реализовать этот поиск?
И какой пользовательский компонент для выбора и ввода директории лучше использовать?Обычную менюшку file->open?
спасибо
Цитата:
Как можно реализовать этот поиск?
вот тебе пример, дальше разбирай сам. в свою програмку прикрутить просто =))) Я его немного переделал, так как у изначального автора Sharon'a Zakhoura он не работал (после 64build'a jdk7 изменилось ряд API).
Ну и использую для этих целей jdk7, пора, уж скоро релиз =))
JDK 7 Preview Release, Milestone 4 -> http://java.sun.com/javase/downloads/ea.jsp
Код:
Цитата:
И какой пользовательский компонент для выбора и ввода директории лучше использовать?Обычную менюшку file->open?
Ну по архитектуре и логике думай сам.
cпасибо