Home > Software engineering >  Java - File IO - AbsolutePath() does not return the path to the file
Java - File IO - AbsolutePath() does not return the path to the file

Time:11-19

I have been trying to get this method working for the past few days always coming back to the same problem. My file won't open unless the file path is specified and formatted.

This is my code:

text = new MyArrayList<>();
    String filePath = new File(fileName).getAbsolutePath();
    filePath = filePath.replace('\\', '/');
    try {
      Scanner s = new Scanner(new File(filePath));
      while (s.hasNext()) {
        text.add(s.next());
      }
      s.close();
    }
    catch(FileNotFoundException e){
      System.out.println("File not found.");
    }

For some reason when I invoke the getAbsolutePath(), it gives me this path : "C:/Zaid/College/CE2336/Programs/File.txt"

whereas the file path that actually allows me to access the file is: "C:/Zaid/College/CE2336/Programs/MyImplementations/File.txt"

I don't understand what I should do to clean this up.

P.S. The MyImplementations is the package where the text file and my code reside in.

CodePudding user response:

When you call

String filePath = new File(fileName).getAbsolutePath();

you are creating file in your root directory of the project and then getting that path instead of the file you already have and want to get

CodePudding user response:

This should be sufficient in your case:

  Scanner s = new Scanner(new File(fileName));

Also ensure when handling errors you share all the information you have: Print the file that was not found. You will see that this makes troubleshooting just so much easier.

catch(FileNotFoundException e){
    System.out.println("File not found.");
    e.printStackTrace(System.out);
}
  • Related