0

I am trying to run a basic scan of a large file, however it keeps giving me a FileNotFound exception however the file is in the same folder as the classes.(Using a mac currently)

import java.io.*;
import java.util.Scanner;
public class LastNameSearch {
    static PopularName[] people= new PopularName[151671];
    public static void main(String[] args){
        String nextString=null;
        PopularName nextName;
        String[] info=new String[5];
        Scanner infile = new Scanner(new FileReader("LastNames.txt"));
        int index=0;
        while(infile.hasNext()){
            nextString=infile.nextLine();
            info=nextString.split(",");
            nextName=new PopularName(info[0], info[1], info[2], info[3], info[4]);
            people[index]=nextName;
        }
        infile.close(); 

new FileReader("LastNames.txt") This line is what is causing me pain. Please Help.

mhully67
  • 1
  • 2
  • Try giving the absolute path. `new FileReader("/.../FileName.txt")` – user2004685 Mar 24 '16 at 06:00
  • just enter an absolute path name. – pvg Mar 24 '16 at 06:00
  • 1. Instead of using new FileReader("LastNames.txt")) ,try wrap your name in a File. ex : new FileReader(new File("LastNames.txt")); 2. Check the file whether it is LastNames.txt or LastNames.txt.txt (default text) – kidnan1991 Mar 24 '16 at 06:03
  • 1
    For the record, when you use a relative path (like you have), that is relative to the [current working directory](https://en.wikipedia.org/wiki/Working_directory). What the current directory is when you run depends on how you run it. For files that get deployed with your code, you should not rely on it to be any particular path; someone could execute your code from anywhere. – jpmc26 Mar 24 '16 at 06:06

2 Answers2

1
  1. place your file under root of your project

    i.e. JetBrains Idea uses project root as working path

or

  1. Use classpath:

    place your file to your_project/main/resources:

URL resource = this.getClass().getResource("/yourfile.txt");
File file = new File(resource.toURI());
Community
  • 1
  • 1
Eugene Lebedev
  • 1,400
  • 1
  • 18
  • 30
0

try to replace

Scanner infile = new Scanner(new FileReader("LastNames.txt"));

with

URL myFile = this.getClass().getResource("LastNames.txt");
Scanner infile = new Scanner(new FileReader(new File(myFile.toURI())));
Raphael Roth
  • 26,751
  • 15
  • 88
  • 145