0

This fails with FileNotFoundException in new Scanner(file):

public class Ex1 {

public static void main(String[] args) {

    // boot.txt -is in its own "resource" source folder in Eclipse
    String fileName = Ex1.class.getResource("/boot.txt").toExternalForm();
    File file = new File(fileName); // File (String pathname) ctor
    Scanner sc;

    try {
        sc = new Scanner(file); // FileNotFoundException here
    } catch (FileNotFoundException e) {         
        e.printStackTrace();
    }       
}

But this runs fine without any Exception (class in same package):

public class Ex2 {

public static void main(String[] args) {

    URL fileURL = Ex2.class.getResource("/boot.txt");
    Scanner sc;

    try {
        File file = new File(fileURL.toURI());  
        sc = new Scanner(file);  // fine!
    } catch (FileNotFoundException | URISyntaxException e) {            
        e.printStackTrace();
    }       
}

What is wrong with

String fileName = Ex1.class.getResource("/boot.txt").toExternalForm();
 File file = new File(fileName);
 Scanner sc = new Scanner(file);

This contributes to "strange" differences between Scanner ctors, but does not answer this question...

Community
  • 1
  • 1
  • Well what's the value of `fileName` in the version that doesn't work? And why do you *want* to go via a `File`? Aside from anything else, that won't work if `boot.txt` is in a jar file etc. – Jon Skeet Mar 04 '17 at 14:40
  • Both are wrong anyway, and won't work as soon as the resource is bundled in a jar/war file for producion. Just use `Ex1.class.getResourceAsStream("/boot.txt")`, and pass the InputStream (and the charset) to the Scanner constructor. – JB Nizet Mar 04 '17 at 14:41

0 Answers0