2
File read = new File("Numbers.txt");
Scanner inputFile = new Scanner(read);

while(inputFile.hasNext())
{
    sum = inputFile.nextDouble() + sum;
    count++;
}

inputFile.close();//close the input file

I'm trying to read data out of the text file Numbers.txt and the following code compiles fine but I get the Java.io.FileNotFoundException error when the program runs. I've also tried entering the full file path but I might have done it wrong. Any ideas?

2
  • This should work fine if file really exists. Probably file name is incorrect. Commented Feb 19, 2013 at 19:52
  • 1
    You are using a relative path, which will be resolved relative to the working directory of the Java program being run. It's always best to specify an absolute path when working with files in Java. Commented Feb 19, 2013 at 19:53

2 Answers 2

2

Make Sure your text file is in the folder with your java file because you used the direct path . and try this code check, if still not working .

BufferedReader read = new BufferedReader(new FileReader("yourTextFile.txt"));
String line = read.readLine();

while(line !=null)
{
     System.out.println(line);
     line=read.readLine();
}
}catch(Exception ex)
{System.out.println(ex.getMessage());}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow thanks. It was the only file not in the folder with the rest. Program works now. Thanks a lot.
1

Try adding

System.out.println("Full path is " + read.getCanonicalPath()
                   + ", canRead=" + read.canRead()
                   + ", exists=" + read.exists());

and then see whether the full path exists on your file system, and whether it is readable according to canRead.

If the file is a symlink, canRead might return true in that the symlink is resolvable even though the file to which the link points is unreadable. To deal properly with symlinks you really need to use the new java.nio.file APIs.

1 Comment

Thanks, this helped me realize that above answer was what was wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.