Click here to Skip to main content
15,896,481 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
i have this program and i want it to find a file not a directory and then search a specific sentence in it and print the name of the file
and i wrote this code and it has FileNotFoundException

C#
public static void main(String[] args)  throws FileNotFoundException{
       // TODO code application logic here
       File file=new File("/Users/amoona/Desktop/MyDir");
 File[] matches = file.listFiles();

  
     for(int i=0;i<file.length();i++){
          Scanner sc=new Scanner (matches[i]);
         if (matches[i].isFile()==true){
              System.out.println("It Is A File");
              while(sc.hasNext()){
              String s=sc.next();

             if ("King AbdulAziz University".equalsIgnoreCase(s)){
                  System.out.println(matches[i].getName());
             }}
           }
       }


   }


What I have tried:

i tried the code above but it has
It Is A File
Exception in thread "main" java.io.FileNotFoundException: /Users/amoona/Desktop/MyDir/Dir1 (Is a directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at lab4.Lab4.main(Lab4.java:38)
/Users/amoona/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
Posted
Updated 25-Mar-16 14:28pm

1 solution

You have an error in your code, so it is trying to process more entries than are returned from the call to listFiles. You should also test for the directory before creating the Scanner object, thus:
Java
public static void main(String[] args)  throws FileNotFoundException{
    // TODO code application logic here
    File file=new File("/Users/amoona/Desktop/MyDir");
    File[] matches = file.listFiles();
    
    
    for(int i=0;i        if (matches[i].isFile()==true){
            // skip this code if entry is a directory
            System.out.println("It Is A File");
            Scanner sc=new Scanner (matches[i]);
            while(sc.hasNext()){
                String s=sc.next();
                
                if ("King AbdulAziz University".equalsIgnoreCase(s)){
                    System.out.println(matches[i].getName());
                }
            }
        }
    }
}

You could also simplify your for loop by using a foreach, thus:
Java
for(File ff : matches){

and use ff in place of matches[i].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900