-1

Why is the following code throwing a No Such File Found Exception? The path is correct and the file does really exist.

Code:

java.util.Scanner s = new java.util.Scanner(
    new File(getClass().getResource("file.txt").getFile())); 
Stewart
  • 17,616
  • 8
  • 52
  • 80
Justix
  • 1
  • 5
  • 4
    The file does not exists. [Check the return value of `getFile()`. If it is empty, the file does not exist](https://docs.oracle.com/javase/9/docs/api/java/net/URL.html#getFile--). – Turing85 Nov 05 '17 at 20:21
  • The error shows the complete correct path. – Justix Nov 05 '17 at 20:31
  • The file exists in eclipse and in my files – Justix Nov 05 '17 at 20:31
  • Why in hell do you transform a classpath resource, which won't be referencing a file once your code will be bundled as a jar or war file, into a File? Just use `new Scanner(MyClass.class.getResourceAsStream("file.txt"))` – JB Nizet Nov 05 '17 at 20:34

2 Answers2

0

I should have used a stream, not a file ..

Code:

java.util.Scanner s = new java.util.Scanner(
    getClass().getResourceAsStream("file.txt")‌​);
Stewart
  • 17,616
  • 8
  • 52
  • 80
Justix
  • 1
  • 5
-1

there is one ) missing at the end of your statement. the correct statement should be as follows:- Scanner s = new Scanner(new File(getClass().getResource("file.txt").getFile()));

If this was not what you were looking for, then probably this is the error scenario that you might be facing. I am assuming that you are writing this block of code in your main() method. As main is marked as static method and you are making use of the getClass() which is a non-static method, you should be getting an error saying "Cannot make a static reference to the non-static method getClass() from the type Object".

also, where exactly have you put your text file?? is the location present in your class path?? if not you will have to include it or you will have to give the complete path of the file in your getResource method.

Probably you can give more insights on the question you posted??

  • The file is in the same folder like the Main class. And I didn't wrote it in the main method, so the code didn't generate other errors. – Justix Nov 05 '17 at 21:13
  • hmmm... that is strange as I have just tried your code and it works just fine. public class file { public void m1() { try { Scanner s = new Scanner(new File(getClass().getResource("file.txt").getFile())); System.out.println("file found!!"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { new file().m1(); } } the file is key inside src/main/java/testpackage/file.txt and this main class is being run from src/main/java/testpackage location. – Deepak Shrivastava Nov 05 '17 at 21:23
  • For me "java.util.Scanner s = new java.util.Scanner(getClass().getResourceAsStream("file.txt"));" worked fine :) – Justix Nov 05 '17 at 21:30