If you put the resource file at the root of your class path (so if the source path for java files is src / main / java, then put the resource file there), then you can do it.
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("myresource.txt")));
Now, if you want, you can put it in a package, so the file will be in src / main / java / com / sksamuel
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("com/sksamuel/myresource.txt")));
Finally, if you use maven or something similar, you should put the file in src / main / resources, not src / main / java, and at compile time the two paths are combined, so you should use the same code as above .
My answer suggests that the file will be packed with your java code and something that the developer will change. If it is generated or needs to be changed outside of jar / war, then this is not the best way.
source share