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\"));
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
Scanner scanner = new Scanner(getClass().getResourceAsInputStream("Words.txt"));
String s = new String();
while(scanner.hasNextLine()){
s = s + scanner.nextLine();
}
InputStream is = MyClass.class.getResourceAsStream("Words.txt");
...
Assuming the text file is in the same directory as the .class
, rather than the .java
file you can do
Scanner scanner = new Scanner(getClass().getResourceAsStream("Words.txt"));
What you have will look for the file in the current working directory. When you are building your program this is typically the root directory of your program. When you run it as a standalone program it is usually the directory the program was started from.