我不确定我是否使用了正确的方法,所以在告诉我我做错了之前,我对新的想法持开放态度。我有一个用于查找文件的目录路径数组。让我们假设所有的示例都是.txt。现在,我在每个目录上运行一个Files.walkFileTree(...),并使用在第一次匹配时停止的SimpleFileVisitor。但现在我想添加一个next按钮,它可以从我停止的地方继续搜索。我该怎么做呢?
我认为我可以将所有的匹配保存在一个数组中,然后从那里读取它,但这会消耗空间和内存。因此,一个更好的想法应该是欣赏。
// example paths content: [/usr, /etc/init.d, /home]
ArrayList<String> paths;
for( String s : paths )
Files.walkFileTree(Paths.get(s), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (alreadyfound >= 10) {
return FileVisitResult.TERMINATE;
}
if (file.toString().endsWith(".txt")) {
System.out.println("Found: " + file.toFile());
}
return FileVisitResult.CONTINUE;
}
});发布于 2016-08-17 21:44:00
我曾经写过一个类,它应该完全按照您的描述来做。我通过在它自己的线程中运行FileVisitor解决了这个问题。当找到一个具有所需扩展名的文件时,它只是停止使用wait()执行,直到一个按钮发出继续使用notify()的信号。
public class FileSearcher extends Thread{
private Object lock = new Object();
private Path path;
private JLabel label;
private String extension;
public FileSearcher(Path p, String e, JLabel l){
path = p;
label = l;
extension = e;
}
public void findNext(){
synchronized(lock){
lock.notify();
}
}
@Override
public void run() {
try {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(file.toString().toLowerCase().endsWith(extension)){
label.setText(file.toString());
synchronized(lock){
try {
lock.wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}如何使用它的一个简单示例如下所示
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel();
FileSearcher fileSearcher = new FileSearcher(Paths.get("c:\\bla"), ".txt", label);
JButton button = new JButton();
button.setText("next");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
fileSearcher.findNext();
}});
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
fileSearcher.start();https://stackoverflow.com/questions/38997032
复制相似问题