Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.HashSet;
- import java.util.Objects;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class FileScanner extends Thread {
- private final String fileToScan;
- //TODO: Initialize the start value of the counter
- private static Long counter = 0L;
- public static Lock lock = new ReentrantLock();
- public FileScanner(String fileToScan) {
- this.fileToScan = fileToScan;
- //TODO: Increment the counter on every creation of FileScanner object
- try {
- lock.lock();
- counter++;
- } finally {
- lock.unlock();
- }
- }
- public static void printInfo(File file) {
- //TODO: Print the info for the @argument File file, according to the requirement of the task
- if (file.isDirectory())
- System.out.printf("dir: %s %d\n", file.getName(), Objects.requireNonNull(file.listFiles()).length);
- else
- System.out.printf("file: %s %d\n", file.getName(), file.length());
- }
- public static Long getCounter() {
- return counter;
- }
- public void run() {
- //TODO Create object File with the absolute path fileToScan.
- File file;
- file = new File(this.fileToScan);
- //TODO Create a list of all the files that are in the directory file.
- File[] files;
- files = file.listFiles();
- // Test test
- HashSet<Thread> newThreads = new HashSet<>();
- for (File f : files) {
- /*
- * TODO If the File f is not a directory, print its info using the function printInfo(f)
- * */
- if (!f.isDirectory()) {
- printInfo(f);
- }
- /*
- * TODO If the File f is a directory, create a thread from type FileScanner and start it.
- * */
- if (f.isDirectory()) {
- printInfo(f);
- FileScanner newFileScanner;
- newFileScanner = new FileScanner(f.getAbsolutePath());
- newFileScanner.start();
- newThreads.add(newFileScanner);
- }
- //TODO: wait for all the FileScanner-s to finish
- }
- for (Thread thread : newThreads) {
- try {
- thread.join();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) throws InterruptedException {
- String FILE_TO_SCAN = "C:\\Users\\Hristijan\\Desktop\\Parent";
- //TODO Construct a FileScanner object with the fileToScan = FILE_TO_SCAN
- FileScanner fileScanner;
- fileScanner = new FileScanner(FILE_TO_SCAN);
- //TODO Start the thread from type FileScanner
- long startTime = System.nanoTime();
- fileScanner.start();
- //TODO wait for the fileScanner to finish
- fileScanner.join();
- long endTime = System.nanoTime();
- //TODO print a message that displays the number of thread that were created
- System.out.println(getCounter());
- System.out.printf("Time of job completion: %fs", (endTime - startTime) * 0.000000001);
- }
- }
Add Comment
Please, Sign In to add comment