Where to place a file in a Java web project?

I have a small java program that reads a file, in eclipse I have a file in the main project, and the class file is in the src directory. It works great.

I want you this little piece of code in the web project I'm working on, I currently have a class file in src / tools /, but have I lost the place to put the file?

I tried it in several places, but it does not delete the file.

Where is the best place to store this file? and how can I guarantee that I have the correct path when using the following code?

FileInputStream fstream = new FileInputStream("file.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
+4
source share
2 answers

You either need to upload the file as a resource (for example, getResourceAsStream() , use the application path ( getRealPath() ), or put it in an absolute location and use the full path.

+2
source

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.

+1
source

Source: https://habr.com/ru/post/1402939/


All Articles