java FileNotFoundException wont locate a file in the same project

5.1k views Asked by At

I am writing a program for my comp sci class, andI keep getting the same error.

Exception in thread "main" java.io.FileNotFoundException: data.txt (No such file or directory)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:120)
    at java.util.Scanner.<init>(Scanner.java:636)
    at Search.main(Search.java:18)

Here is the beginning of my code:

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.IOException;
public class Search{
    public static void main(String[] args)throws IOException{
        Scanner inData = new Scanner(new File("data.txt"));

        String data=inData.nextLine();
        String[] arr = data.split(" ");   

        while(inData.hasNext()){
            String search=inData.nextLine();
            int len=search.length();
            ArrayList<String> result = new ArrayList<String>();

I have a text file in the same Java Project, so I'm not sure what the problem is and I've tried moving the location of the file around but nothing is working.

2

There are 2 answers

2
B4dT0bi On

The working path of your executed code can be determined with this code:

System.out.println(new File(".").getAbsolutePath());

Usually this is the target or the classes or the bin folder, depending on your IDE.

5
AudioBubble On

You have to put the file data.txt in the root of your eclipse java project , outside your folder /src/.

enter image description here