0

I'm pretty new to using Java and programming in general, and I can't for the life of me figure out how to find the text file below. I saved it in the files folder within the project and it still doesn't work. People have suggested using absolute paths and I tried that to no avail, and I don't know if I'm just screwing up the path or if I have to do something else. All of the absolute path examples I've found on here are using Windows, and the root folder looks like "C:/../whatever.txt". Is there something different one has to do on a Mac?

I've gone to the Relative/Absolute paths thread already, and in spite of following the directions on there is still an error.

This is my code...and the error happens on the Scanner line when it doesn't find the txt file. Help?

import java.util.Scanner;
import java.io.File;

public class Paper {

        public static void main(String[] args) {

        File place = new File("wrappingPaper.txt");

            Scanner scan = new Scanner(place);
            System.out.println("found it");
    }

}

  • Don't worry. You aren't being abandoned. Could you let me know what happens when you try getting rid of the ".txt"? – Monkeygrinder Dec 04 '15 at 20:10
  • Nothing, same error message on the Scanner line. "Unhandled FileNotFoundException" – John Culbreth Dec 04 '15 at 20:16
  • Okay. I asked because depending on how the file is saved, the ".txt" extension may or may not be appended to the filename. Ah!!! Got it. Try adding `throws FileNotFoundException` after `main(String[] args)`. – Monkeygrinder Dec 04 '15 at 20:19
  • You may not have learned about Exceptions yet, but there is a type called a checked exception. If a checked exception is not handled, the compiler will not allow the program to run. One way to handle an exception is by using a `throws` declaration. Another way is using a try catch block – Monkeygrinder Dec 04 '15 at 20:21
  • Oh wow, so I made the wrong assumption about the error. Learned a lesson today. Thanks @Monkeygrinder! – John Culbreth Dec 04 '15 at 20:27
  • np. `throws` is more or less like saying "let the next guy handle it". Since this is your main method though, you're basically saying "the compiler can take care of it" (it can't), so if the file can't be found, it will throw the exception anyway and the program will terminate. As mentioned, you can use a try catch block to deal with an exception in the method itself (and prevent abnormal termination, for that matter), but for the time being adding `throws` here will, in a sense, trick the compiler into thinking it's being handled. There are probably much better explanations out there though. – Monkeygrinder Dec 04 '15 at 20:33

0 Answers0