Java - Getting file from same package

2019-04-19 11:55发布

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.

4条回答
ら.Afraid
2楼-- · 2019-04-19 12:15
Scanner scanner = new Scanner(getClass().getResourceAsInputStream("Words.txt"));

String s = new String();

while(scanner.hasNextLine()){


        s = s + scanner.nextLine();


 }
查看更多
爷的心禁止访问
3楼-- · 2019-04-19 12:16
InputStream is = MyClass.class.getResourceAsStream("Words.txt");
...
查看更多
一夜七次
4楼-- · 2019-04-19 12:24

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.

查看更多
疯言疯语
5楼-- · 2019-04-19 12:29
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

查看更多
登录 后发表回答