问题
The file is in my project, and named correctly, I am quite new to JAVA. Any hints would be appreciated, TIA.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ExceptionsAndCarryOn {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
Scanner UserInput = new Scanner(new File("Numbers.txt"));
System.out.println("Please enter the numbers: ");
int [] numbers = new int [5];
int i = 0;
while(UserInput.hasNextInt()){
numbers[i++] = UserInput.nextInt();
}
int sum = 0;
for ( i = 0; i < numbers.length; i++)
sum += numbers[i];
System.out.println(sum);
UserInput.close();
}
}
回答1:
Put the file Numbers.txt in the project folder , parallel to the src folder. not inside the src folder.
That will solve your problem . Since you are not providing the fully qualified name (absolute path) . the JRE will assume that the file should be in the project folder from where your application is being run.
You can put the file in any folder and use fully qualified names like:
Scanner UserInput = new Scanner(new File("D://Sunit//Numbers.txt"));
回答2:
You stated that the file is in your project/src folder. That is where the source files are present, not executed.
When the .java files are compiled, the bytecodes (.class files) are stored in the build/classes directory. You may keep the Numbers.txt there, but it will be deleted once you give the clean and build option.
You have two alternatives:
Change the path in the code to "../../src/Numbers.txt"
Move the Numbers.txt anywhere and give the absolute path.
回答3:
various possibilities could cause this issues, check these:
- file is in the current working directory
- file has that specific name and extension
- if you're using windows enable the "show extension for hidden files" property from the settings. otherwise it could happen that Numbers.txt.txt is the actual name
来源:https://stackoverflow.com/questions/40930397/file-not-found-error-in-java-file-is-in-my-project-folder