File not found error in java, file is in my project folder?

 ̄綄美尐妖づ 提交于 2019-12-25 04:04:06

问题


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:

  1. Change the path in the code to "../../src/Numbers.txt"

  2. Move the Numbers.txt anywhere and give the absolute path.




回答3:


various possibilities could cause this issues, check these:

  1. file is in the current working directory
  2. file has that specific name and extension
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!