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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
package thread;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
public class QueueDeBlocage {
private static final int THREADS_DE_RECHERCHE = 100;
private static String répertoireDeBase;
public static void main(String[] args) {
Scanner clavier = new Scanner(System.in);
System.out.print("Le Dossier de la recherche : ");
répertoireDeBase = clavier.nextLine();
System.out.print("Le mot à rechercher : ");
String motDeRecherche = clavier.nextLine();
BlockingQueue<File> queue = new LinkedBlockingQueue<File>();
EnumérationFichiers fichiers = new EnumérationFichiers(queue, new File(répertoireDeBase));
new Thread(fichiers).start();
for (int i = 1; i <= THREADS_DE_RECHERCHE; i++)
new Thread(new TâcheDeRecherche(queue, motDeRecherche)).start();
}
}
class EnumérationFichiers implements Runnable {
private BlockingQueue<File> queue;
private File répertoire;
public static File VIERGE = new File("");
public EnumérationFichiers(BlockingQueue<File> queue, File répertoire) {
this.queue = queue;
this.répertoire = répertoire;
}
public void run() {
try {
énumère(répertoire);
queue.put(VIERGE);
}
catch (InterruptedException e) {}
}
public void énumère(File répertoire) throws InterruptedException {
File[] fichiers = répertoire.listFiles();
for (File fichier : fichiers) {
if (fichier.isDirectory()) énumère(fichier);
else {
queue.put(fichier);
System.out.printf("Lecture du fichier %s\n", fichier.getPath());
}
}
}
}
class TâcheDeRecherche implements Runnable {
private BlockingQueue<File> queue;
private String mot;
public TâcheDeRecherche(BlockingQueue<File> queue, String mot) {
this.queue = queue;
this.mot = mot;
}
public void run() {
try {
boolean fini = false;
while (!fini) {
File fichier = queue.take();
if (fichier == EnumérationFichiers.VIERGE) {
queue.put(fichier);
fini = true;
}
else recherche(fichier);
}
}
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { }
}
public void recherche(File fichier) throws IOException {
Scanner lecture = new Scanner(new FileInputStream(fichier));
int nombreLigne = 0;
while (lecture.hasNextLine()) {
nombreLigne++;
String ligne = lecture.nextLine();
if ( (ligne.contains(mot.toLowerCase())) || (ligne.contains(mot.toUpperCase())))
System.out.printf("%s:%d:%s%n", fichier.getPath(), nombreLigne, ligne);
}
lecture.close();
}
} |
Partager