Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Getting file from same package

Tags:

java

file

package

If I want to read from "Words.txt" which is in the same package as the class, how would I do this? Doing simply Scanner = new Scanner(new File("Words.txt")); returns an error.

like image 353
Ronan H Avatar asked Sep 14 '12 16:09

Ronan H


2 Answers

InputStream is = MyClass.class.getResourceAsStream("Words.txt");
...
like image 173
Jiri Kremser Avatar answered Oct 07 '22 01:10

Jiri Kremser


Scanner = new Scanner(new File("/path/to/Words.txt")); 

The argument in the File() constructor, Is the path relative to the system your VM is running on, it s doesn't depend on the classe's package.

If you your words.txt is a resource packaged with your war you can see here : Load resource from anywhere in classpath

like image 23
Majid Laissi Avatar answered Oct 06 '22 23:10

Majid Laissi