Tony Stark Tony Stark - 1 year ago 74
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:

Exception in thread "main" C:\TestData\data.txt (The system cannot find the file specified)
at Method)
at test.Count.main(
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 file is


public class Count {

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

while ( != -1) {

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

enter image description here

enter image description here

Answer Source

I tested your code and it runs fine.

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download