0

I'm new to programming, every time I try to read a file. I get FileNOtFoundException.

Where could I be going wrong?

import java.io.*;
import java.util.Scanner;

public class ReadFile 
{
    public ReadFile()
    {
        readFile();
    }
    public void readFile()
    {
        String filename = "trees.txt";
        System.out.println(new File(".").getAbsolutePath()); //file is at this path.
        String name = "";
        try
        {
            FileReader inputFile = new FileReader(filename);
            Scanner parser = new Scanner(inputFile);
            while (parser.hasNextLine())
            {
                name = parser.nextLine();
                System.out.println(name);
            }
            inputFile.close();
        }
        catch (FileNotFoundException exception)
        {
            System.out.println(filename + " not found");
        }
    }
}

Is there any other way I could read the file?

2 Answers2

0

this code

FileReader inputFile = new FileReader(filename);

You must define full path to file with name filename if not it will open file not at current working directory you should try

FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory  

you can read more at: Java, reading a file from current directory?

0

Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location

String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());

Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources

petrubear
  • 616
  • 5
  • 6