aboutsummaryrefslogtreecommitdiff
path: root/Week12 Find File/src/com/camilstaps/findfile/FileFinder.java
blob: 80e06da8579769faa3959721bf883ae4d01ebd2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 * Copyright (c) 2015 Camil Staps
 */
package com.camilstaps.findfile;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author camilstaps
 */
public class FileFinder implements Runnable {
    
    private final File rootDir;
    private final String search;
    
    public FileFinder(String root, String search) throws IOException {
        rootDir = new File(root);
        if (!rootDir.exists() || !rootDir.isDirectory()) {
            throw new IOException(root + " is not a directory.");
        }
        
        this.search = search;
    }

    @Override
    public void run() {
        find(rootDir, search);
    }
    
    private void find(File dir, String name) {
        File[] files = rootDir.listFiles();
        if (files == null) return;
        for (File file : files) {
            if (file.getName().equals(name)) {
                System.out.println(file.getAbsolutePath());
            }
            if (file.isDirectory()) {
                try {
                    Thread t = new Thread(new FileFinder(file.getAbsolutePath(), search));
                    t.start();
                    t.join();
                } catch (IOException | InterruptedException ex) {}
            }
        }
    }
    
}