Search code examples
javatextfilenotfoundexceptionfile-read

Unable to read simple text file Java


Hi I've been asked to write code that will read a text file in the same directory as my .class file. I've written a simple program that reads "input.text" and saves it to a string.

/** Import util for console input **/
import java.util.*;
import java.io.*;
/** Standard Public Declarations **/
public class costing
{
    public static void main(String[] args)
    {
        Scanner inFile = new Scanner(new FileReader("Coursework/input.txt"));
        String name = inFile.next();
        System.out.println(name);
    }
}

Gives the error:

10: error: unreported expection FileNotFoundExcpetion; must be caught or declared to be thrown

I've tried input.txt in the same folder and one level above but still no luck.

Thanks!!


Solution

  • Well, there are two types of exception - unchecked and checked. checked are the ones that are checked at compile time. So, when compiler says "10: error: unreported expection FileNotFoundExcpetion; must be caught or declared to be thrown" It means line inFile = new Scanner(new FileReader("input.txt")); throws checked exception which means that this method has an underlying risk that it can throw a FileNotFoundExceptionand hence you should handle it. So, wrap your code in try/catch block -

    /** Import util for console input **/
    import java.util.*;
    import java.io.*;
    /** Standard Public Declarations **/
    public class costing
    {
     public static void main(String[] args)
     {
    
      Scanner inFile;
      try {
         inFile = new Scanner(new FileReader("Coursework/input.txt"));
         String name = inFile.next();
         System.out.println(name);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    }
    }
    }
    

    It might throw a runtime error if it did not find input.txt in the correct directory.