Search code examples
javafilefileinputstream

java FileInputStream cannot find file


I'm very new at coding java and I'm having a lot of difficulty. I'm suppose to write a program using bufferedreader that reads from a file, that I have already created named "scores.txt". So I have a method named processFile that is suppose to set up the BufferedReader and loop through the file, reading each score. Then, I need to convert the score to an integer, add them up, and display the calculated mean.

I have no idea how to add them up and calculate the mean, but I'm currently working on reading from the file. It keeps saying that it can't fine the file, but I know for sure that I have a file in my documents named "scores.txt".

This is what I have so far...it's pretty bad. I'm just not so good at this :( Maybe there's is a different problem?

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

String file = "scores.txt";
processFile("scores.txt");
//calls method processFile
}


public static void processFile (String file)
throws IOException, FileNotFoundException{
String line;
//lines is declared as a string


   BufferedReader inputReader =
           new BufferedReader (new InputStreamReader
    (new FileInputStream(file)));

   while  (( line = inputReader.readLine()) != null){
   System.out.println(line);

  }    
  inputReader.close();
   }

Solution

  • There are two main options available

    1. Use absolute path to file (begins from drive letter in Windows or slash in *.nix). It is very convenient for "just for test" tasks.

      Sample Windows - D:/someFolder/scores.txt, *.nix - /someFolder/scores.txt

    2. Put file to project root directory, in such case it will be visible to class loader.