I’m new to the programming world, and I am trying to do a simple program where I read and output a single number from a file. I believe I set everything up right in the code, do I need to do anything special with the location of the .txt file to make the program read the file?
package pack;
import java.util.*;
import java.io.*;
public class Ch2_PrExercise17 {
public static void main(String[] args)
throws FileNotFoundException{
Scanner inFile = new Scanner(new FileReader("inData.txt"));
int num1;
num1 = inFile.nextInt();
System.out.println(num1);
}
}
The exception I get is as follows;
Exception in thread "main" java.io.FileNotFoundException: inData.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at pack.Ch2_PrExercise17.main(Ch2_PrExercise17.java:8)
If Eclipse is really saying “source not found” then it is talking (at that point) about the source code of something.
If you are managing to run the class from Eclipse, then Eclipse has been able to compile it, so it knows where the source code is. So it must be the source code of something else. My best guess is that it can’t find the source code for the standard Java class library, and that probably means that Eclipse is running on a JRE installation not a JDK installation.
(If my theory is correct, then the “source not found” text is embedded in the exception stacktrace …)
It might also be a build problem but I doubt it, because if the class wasn’t building you’d see error markers when you view the source file in eclipse, and Eclipse would complain when you tried to run it. Eclipse would also complain if the source file was in the wrong directory.
The second part of the problem is getting your application to find the
"inData.txt"file. That should be simple. When you try to open a file with a relative pathname, the Java libraries will try to resolve the pathname relative to the application’s “current directory”. By default, when you run the application from Eclipse, this will be the directory your shell was in when you launched Eclipse; e.g.… and the default current directory should be “/home/josh/somedir”.
If the default current directory is not right, you have a number of options, including:
FOLLOW-UP
The “Unknown Source” messages mean that the JVM (not Eclipse) cannot find the information it needs to produce a full stacktrace. You appear to be executing using an “rt.jar” file that has debug information stripped. You can ignore this issue, but to fix it you would need to look into what JVM is being uses, and why the “rt.jar” has no debug info.
The real problem is the
FileNotFoundExceptionexception, and my diagnosis of that (as above) stands. The “current directory” is not what it needs to be for that relative pathname to resolve. See above for possible solutions.