I am trying to find how often a specific String repeats itself in an external directory. This is the code I currently have:
package Files;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class StringSearcher {
public static void main(String[] args) throws FileNotFoundException {
Scanner searcher = new Scanner(System.in);
Boolean foundString = false;
System.out.println("Enter the word you would desire to search");
String word = searcher.next();
int count = 0;
System.out.println("Contents of the line");
// Reading the contents of the file
Scanner sc2 = new Scanner(new FileInputStream("/Users/ricardobarahona/Desktop"));
while (sc2.hasNextLine()) {
String line = sc2.nextLine();
System.out.println(line);
if (line.indexOf(word) != -1) {
foundString = true;
count = count + 1;
}
}
if (foundString) {
System.out.println("File contains the specified word");
System.out.println("Number of occurrences is: " + count);
} else {
System.out.println("File does not contain the specified word");
}
}
}
My directory works but this is the error I keep receiving:
Exception in thread "main" java.io.FileNotFoundException:
/Users/ricardobarahona/Desktop (Is a directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:216)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:111)
at Files.StringSearcher.main(StringSearcher.java:16)
>Solution :
Try changing every occurance of FileInputStream to File. It should get rid of the error and it also should be able to read the file properly