Tony Stark Tony Stark - 1 month ago 9
Java Question

Running a program that read a file and count the characters in the file results in FileNotFoundException

I'm trying to read a file and count the number of characters within file. Below is my code. However, whenever I run the code, NetBeans always output the following error message:

run:
Exception in thread "main" java.io.FileNotFoundException: C:\TestData\data.txt (The system cannot find the file specified)
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.io.FileInputStream.<init>(FileInputStream.java:93)
at test.Count.main(Count.java:28)
C:\Users\Justin\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1


Why is this happening? Is there something I'm missing?

Location of Count.java file is
C:\Test\src\test\Count.java


import java.io.*;

public class Count {

public static void countChars(InputStream in) throws IOException {
int count = 0;

while (in.read() != -1) {
count++;
}

System.out.println("Counted " + count + " chars.");
}

public static void main(String[] args) throws Exception {

countChars(new FileInputStream("C:\\TestData\\data.txt"));

}
}


Location of data.txt is
C:\TestData\


enter image description here

enter image description here

Answer

I tested your code and it runs fine.

Try to use a directory with access rights, like your home folder.

C:\TestData\data

Are you sure that you created a data.txt file and not a data (without extension) accidently?