1

I am in the process of switching from Eclipse to IntelliJ. I have included a file "input.txt" in my project, but I am getting a FileNotFoundException when I write Java code to access it. What am I doing wrong?

FileNotFoundException

3 Answers 3

5

It's not the issue, that the file could not be found in IntelliJ. It's the fact, that your compiler says, that the file could possible not found at runtime. So you have to handle the FileNotFoundException with a try-catch block around like this:

try { BufferedReader reader = new BufferedReader(new FileReader("./input.txt")); // read the file // ... } catch (FileNotFoundException e) { // do something, when the file could not be found on the system System.out.println("The file doesn't exist."); } catch (IOException e) { // do something, when the file is not readable System.out.println("The file could not be read."); } catch (/* other exceptions... */) { // do something else on some other exception // ... } 

Of course, you already know, that the file will be found, but not the compiler!

Basically read about Exceptions: http://docs.oracle.com/javase/tutorial/essential/exceptions/

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it's true that I did not handle the exception.. but now when I run the program, I see the error message: "The file doesn't exist."
1

You should either specify the full path to the file or run the program so that its working directory contains this file. The second can be achieved if you go to your run configuration settings and ensure that Working DIrectory field is pointing to Hexagram directory.

Comments

0

You can also throw the FileNotFoundException into your main method, your output just won't be as pretty.

public static void main(String[] args) throws FileNotFoundException { 

1 Comment

This doesn't really address why the error is being thrown. Consider entering it as a comment on the question instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.