Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error Trying to fin iterations of a String from a File in my Desktop in Java

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading