Java - Getting file from same package

2019-04-19 12:05发布

问题:

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.

回答1:

InputStream is = MyClass.class.getResourceAsStream("Words.txt");
...


回答2:

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



回答3:

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.



回答4:

Scanner scanner = new Scanner(getClass().getResourceAsInputStream("Words.txt"));

String s = new String();

while(scanner.hasNextLine()){


        s = s + scanner.nextLine();


 }