Input file not found

I just fiddled with reading input files with java until I was stumped on the simplest steps ... find the input file!

The input.txt file is in the same directory as my class file that calls it, but eclipse still gives me an error that cannot be found:

"Exception on stream" main "java.lang.Error: Unresolved compilation problem: Unhandled FileNotFoundException exception type"

My code:

package pa;
import java.util.Scanner; 

public class Project {
 public static void main(String[] args) {
    java.io.File file = new java.io.File("input.txt");
    System.out.println(file.getAbsolutePath());
    Scanner input = new Scanner(file);
 }
}

      

input.txt is in the same package, in the same folder and in everything. I am embarrassed: (

+3


source to share


5 answers


I don't know about eclipse, but in netbeans the path does not start with the package (folder) of your class, but in the root folder of your project. To find this file in netbeans you need to put new File("src/pa/input.txt")

.



+4


source


Try using an absolute file path like:

java.io.File file = new java.io.File("C:\\My Documents\\User\\input.txt");

      

Also declare the method main()

like this:



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

      

Usually you want to catch and handle the exception, but for now, just throw it.

+1


source


When using eclipse, the working directory is the project directory, not the class directory.

You can get the working directory in the following way:

File f = new File(".");
System.out.println(f.getAbsolutePath());

      

+1


source


The "Unhandled FileNotFoundException" error can be resolved by handling exceptions in your main () method. Add the following command to your code.

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

      

Run the program and you should get the location of the input.txt file.

You can read more about exception handling here.

Greetings

+1


source


See the folder where the class files are generated. If the input.txt file is not in that folder, put it there and try running the code again.

0


source







All Articles