-2

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!!

Ed Byrne
  • 29
  • 1
  • 6

4 Answers4

0

you have to use an exeption in your code put your code between:

try
{

  Scanner inFile = new Scanner(new FileReader("Coursework/input.txt"));

  String name = inFile.next();

  System.out.println(name);

}

catch( FileNotFoundExcpetion e)
{

}
brso05
  • 13,142
  • 2
  • 21
  • 40
user3521250
  • 115
  • 3
  • 14
0

put your code in try ctach blocks the code :Scanner inFile = new Scanner(new FileReader("Coursework/input.txt")); is throws an exception and toy should handle it before compiling your code

void
  • 7,760
  • 3
  • 25
  • 43
0

Use this code snippet to get your .class directory:

URL main = Main.class.getResource("Main.class");
  if (!"file".equalsIgnoreCase(main.getProtocol()))
  throw new IllegalStateException("Main class is not stored in a file.");
  File path = new File(main.getPath());
  Scanner inFile = new Scanner(new FileReader(path + "/input.txt"));
  String name = inFile.next();
  System.out.println(name);

More info here.

Community
  • 1
  • 1
0

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.

Ouney
  • 1,164
  • 1
  • 10
  • 22