Question

I am using Eclipse and am in the early stages of learning Java

Busy learning how to read data from a txt file but can't for the life of me get Java to read the my source file

Here is my code

import java.io.FileReader;
import java.util.Scanner;

public class MagellanSchoolQ2Coursework2 {

public static void main(String[] args) {

    Scanner detailsIn =new Scanner(new FileReader("c:\\s.txt"));
    detailsIn.close();
}

}

The text file is sitting in the root directory of my C drive but for some reason I get a FileNotFoundException

Does anyone know why this is not working

Was it helpful?

Solution

You must either surround your method with a try/catch or add a throws clause to your method.

E.g.

import java.io.FileReader;
import java.util.Scanner;


public class MagellanSchoolQ2Coursework2 {
    public static void main(String[] args) {
        try {
            Scanner detailsIn =new Scanner(new FileReader("c:\\s.txt"));
            detailsIn.close();
        } catch (FileNotFoundException e) {
            System.out.println("file not found: s.txt");
        }
    }
}

OTHER TIPS

Actually the constructor which you are using for creating a FileReader instance ,It's signature is as shown below

public FileReader(String fileName) throws FileNotFoundException

Creates a new FileReader, given the name of the file to read from.

Parameters: fileName - the name of the file to read from

Throws: FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.

As this method throws "FileNotFoundException" it should be handled using try and catch blocks (or) the main method should throw the above exception which will be handled by JVM during run time.If you are new to EXCEPTIONS study that topic better first and after that try learning I/O streams.

This is an operating system problem, I think. Because I use this form in Linux: "c:\s.txt", but in Windows I use it in a little bit different version: "c:\s.txt" Let's try it! :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top