File not found in Java

  1. Hello. I am having some trouble getting a java program to work. I am supposed to make a program that takes a word and a file name, and finds all lines in that file that contain that word.

    The word that I chose was "try", and the file was "Sgrep.java"

    Here is the main method:

    Code (Text):
    class main {
    public static void main(String[] args){
            if(args.length != 2){
                System.out.println("Usage: java Sgrep <string> <filename>");
                return; }
            Sgrep task = new Sgrep(args[0], args[1]);
            System.out.println(task.getFilename());
            System.out.println(task.search());
        }
        }
    and here is the class Sgrep:

    Code (Text):
    import java.io.*;
    public class Sgrep {
        String find;
        String file;
        Sgrep(String fin, String fil)
        {
            find=fin;
            file=fil;
        }
        public String getFilename() {
            return file;
        }
        public String search() {
            FileReader read;
            String currentLine;
            String answer = "";
            if(find == null) {return "";}
            try {
                read = new FileReader(file);
            }
            catch (FileNotFoundException e) {return "File not found";}
            LineNumberReader reader = new LineNumberReader(read);
            while(0==0) {
                try {
                    currentLine = reader.readLine();
                } catch (IOException ex) {
                    return answer;
                }
                if(currentLine.indexOf(find) != -1) {answer = answer + "\n" +
                        reader.getLineNumber() + ":\t" + currentLine;}            
            }
        }
    }
     
    I put a return statement after the FileNotFoundException that prints "File not found", and that is what I have been getting.

    Did I do anything wrong that is not allowing the program to find the file? Because it is supposed to work.

    I would appreciate any help,
    Jeans

    This is important, I need this done by this weekend.


    EDIT: I got it to work. The assignment sheet had given an example output that showed the file name as Sgrep.java, however, in order to get the program to recognize the file, I had to type in the entire target (C:\Users\User\Sgrep\src\sgrep\Sgrep.java). That is two hours of my life I'll never see again :biggrin:.
     
    Last edited: Mar 22, 2008
  2. jcsd
Know someone interested in this topic? Share this thead via email, Google+, Twitter, or Facebook

Have something to add?

0
Draft saved Draft deleted