user2088547
user2088547

Reputation: 23

Java.io.FileNotFoundException using File object

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?

Upvotes: 2

Views: 1301

Answers (2)

Azad
Azad

Reputation: 5055

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());}

Upvotes: 2

Mike Samuel
Mike Samuel

Reputation: 120586

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.

Upvotes: 1

Related Questions