Reputation: 1
I was doing a programming assignment that involves reading from a file that contains employee data and am required to write a program that throws an IOException. When I tried to read from the file, which is located in the same folder as the Java file I'm writing, it gave me a FileNotFoundException. Here's my code so far:
import java.util.*;
import java.io.*;
public class main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Employee[] employees = new Employee[19];
File infile = new File("employeeData.txt");
Scanner inputFile = new Scanner (infile); // FileNotFoundException
// thrown here
}
The first few lines of the text file employeeData.txt, which is located in the same folder as my main.java file:
// Type of employee; name; ID
Hourly;Adam White;200156;12.75;40 // then pay rate; hours
Salaried;Allan Westley;435128;38500.00 // then annual salary
Supervisor;Annette Turner;149200;75000.00;5000;435128 614438 435116 548394 // then salary; bonus; ID's of employees who report to her
I expected that it would read the text file that I've previewed above as it's in the same folder, but it just gave me a FileNotFoundException.
Upvotes: 0
Views: 110
Reputation: 2027
This happens because the JVM tries to look for your file in the current working directory which is usually the project root folder and not the src
folder.
You can adjust your relative path to the file to reflect that or you can provide an absolute path.
If you want to know where it is looking for you file, you can put System.out.print(infile.getAbsolutePath());
right after the creation of the File
object.
Solution with relative path:
public static void main(String[] args) throws IOException
{
Employee[] employees = new Employee[19];
File infile = new File("src/employeeData.txt");
Scanner inputFile = new Scanner(infile);
}
Solution with absolute path:
public static void main(String[] args) throws IOException
{
Employee[] employees = new Employee[19];
File infile = new File("C:/PATH_TO_FILE/employeeData.txt");
Scanner inputFile = new Scanner(infile);
}
Upvotes: 0
Reputation: 3862
you need to give file path from Project's root
folder, so if your file is under src
the path will be : src/employeeData.txt
Upvotes: 1