File relative path is not taken in spring boot - java

I have created json file inside resources dir in spring boot application. File path is like: resources/recipe/recipe.json
When i use relative path, it won't be taken by java compiler so i'll get this exception.
java.io.FileNotFoundException: recipe/recipe.json (No such file or directory).
But this path is identified by IDE. if i click the path, it will be redirected to json file. Can anyone tell what the issue is ?
(FYI: absolute path is working perfectly)

If you have the resources folder in your classpath, then you should use Spring's Resource classes and specify the resource location as
classpath:recipe/recipe.json
You probably want to read this answer:
Spring Boot - Reading Text File using ResourceLoader

If your resouce is present inside resources/static/listing.csv
String path = "classpath:static/listings.csv";
ResultSet rs = new Csv().read(path, null, null);

If you need to access a file which is not in the classpath, you can provide the relative path from the root module directory.
E.g.
new File("src/main/resouces/recipe/recipe.json");

Related

Why is Spring Boot's resource precedence ignoring my external properties files?

As part of a Spring Boot project I need to load certain properties file which, by default, is located under de src/main/resources directory. Also, I need to be able to, instead, load an external properties file (located at the root directory of the project). If this external file exists, the file path should be passed as command line property.
The file structure would be like this:
/app_project
Net.properties (external file)
/src
/main
/resources
Net.properties (default file)
The thing is that the dependency that makes use of those properties wouldn't work unless you copy/overwrite the contents of the external file into the file under the /resources directory.
UPDATED
So far I've tried:
loading the file as an external resource and loading it into a Properties object (https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html)
saving the properties as System Properties
modifying the resource handler to look into other directories by overriding th addResourceHandlers() to include the location
Explicitly including the location of the file in the CLASSPATH with the -cp argument (as #veysiertekin suggested)
Loading it as a #PropertySource (as suggesed by #Nikolay Shevchenko)
Overriding the Spring Boot's config location with the spring.config.location (as suggested by #gWombat)
With all these methods I've tried, the file is indeed read and loaded but, at some point, and every time, the app resorts to the file under src/main/resources .
I suspect it may have to do with the precedence of the file (as described here https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html), but I just couldn't figure out what's happening.
Thanks in advance for your help.
Try smth like
#PropertySources({
#PropertySource(name = "default", value = "classpath:default.properties"),
#PropertySource(name = "external", value = "classpath:external.properties", ignoreResourceNotFound = true)
})
public class YourSpringBootApplication {
...
}
Based on the official doc, you can try to use the propertyspring.config.additional-location to add additional config file , or spring.config.location to override default file location.
You should pass those properties as program arguments so that Spring can use them on application startup.
When spring-boot project is running, it checks files under the builded jar file. You need to add your external file to classpath before running the application:
java -cp 'path-to/spring-boot-application.jar:Net.properties' test.SpringBootApplicationMain

How to create a file in webroot during runtime in java web project?

Hi i must create a XML file in the project using java dynamically and must read it using the base Path URL. i can read the File when i create it manually, but not able to create it dynamically. When i use File f1 = new File("test.XML"); it create the file in the tomcat's Bin folder. The file must be created in the Project while Running in both Tomcat and Jboss EAP 6.
You can get the real path of the web application using the servlet context:
new File( servletContext.getRealPath( "/text.XML" ) );
Note: if you're running tomcat/jboss on Linux, you'll probably have to give permission to write in the webapp folder though, which is most likely forbidden by default.
Quoting from Servlet API docs of ServletContext.getRealPath():
Returns a String containing the real path for a given virtual path.
For example, the path "/index.html" returns the absolute file path on
the server's filesystem would be served by a request for
"http://host/contextPath/index.html", where contextPath is the context
path of this ServletContext..

How to access a file under WEB-INF folder in java class

I have a plain java class in a web application and want to read a configuration file under WEB-INF folder. I know the way to access the file if its in the classpath (WEB-INF/classes folder). Since WEB-INF/classes folder is meant for .class files, I want to keep my configuration file under WEB-INF folder only.
Can anyone tell me how I can access it from my java class?
ServletContext.getResourceAsStream() will load a file from a given path relative to the root of the WAR file. Something like:
ServletContext ctx;
InputStream configStream = ctx.getResourceAsStream("/WEB-INF/config.properties");
The major issue here is that you need access to the servlet context to be able to do this. You have that in a servlet or a filter, but not in a non-web component further back in the application. You have a few options:
Make the servlet context available from the web layer to the service layer, via an application-scoped variable, or injection, or some other way
Put the resource-loading code in the web layer, and expose that to the service layer
Load the configuration in the web layer, and pass it on to the service layer
You can get the absolute path of servlet using getRealPath() method of ServletContext and then append WEB-INF to the path you get. I think this is very basic there may be some other answers as well.
hey you all care for context related file loading like application context , web.xml ,config and property file
Here is how to load a java file any kind of file under WEB-INF but it stored on another stucture like a sub folder reportFile the your file or sub folder again report01--
fullpath is = /WEB-INF/reportFile/report01/report.xml ,i have tried many possibilities to load and read this xml file ...none of the above worked for me but , here is the trick for future use...
In Action or inservice class you know interface implementation class no imports that is good part also.
declare your file object
File myClass = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getFile());
System.out.println("Finding calss path first then remove classes from the path " + myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFIle/report01/reports.xml")
2.Load the path by removing classes from the above and add your specific path
File f = new File(myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFile/report01/reports.xml")
Then
you can even parse it using xml parser or do anything
document = docBuilder.parse(new File(myClass.getCanonicalPath().replaceFirst("classes", "")+"reportFile/report01/reports.xml"));
Cheers!!
"new FIleInputStream(
Utility.class.getClassLoader().getResource(keyFileName).getPath()
)"
worked for me.
Here "Utility" is my class name where the code is calling this line , "keyFileName" is the file i need to open

How to read a directory in webapp folder of Maven web application

I'm working in maven web application. I need to read a directory(For ex: Files) in my webapp folder as follows,
Java.io.File file = new Java.io.File("path");
But I don't know how to specify the path of the directory here.
You shouldn't give local path addresses. Path should be a relative address, e.g. /files/images under your web archive (.war) folder.
To use relative paths properly, I suggest you to add your target folder to the resources definiton of POM.xml, check out these pages
http://www.mkyong.com/maven/how-to-change-maven-resources-folder-location/
http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
You can refer to resources folder easily with something like this:
this.class.getResource("Mydirectory/SubDirectory");
When in doubt how relatives paths work, it's always best to do something like that:
System.out.println(new File("/my/desired/directory").getAbsolutePath());
This will print out the path in which classpath will look for the files.
Assuming:
servlet container webapps dir is located in: /var/lib/tomcat6/webapps
your webapp is called my-webapp.war
You should see the following output: /var/lib/tomcat6/webapps/my-webapp/my/desired/directory
Another pointer: you have mentioned that you are looking for webapp directory. I hope you know that this directory will not end up in *.war - it's contents will.
War files are not always expanded when they are deployed to an app server, so it's possible that a relative path won't exist in a filesystem at all.
Best bets are to use getResource from the class loader, which will return things in the class path (the WEB-INF/lib directory, etc), or to use the getResource() method of ServletContext to find things in the web application itself.

WEB-INF path for files

I have web application with configuration files in \WEB-INF\etc\config. This folder contains a few property files and one xml. I need to set up path to xml in one property file. After setuping this file is using to create object during start of service, this object reads properties from file. So, this object has to know path to the all files that was described in property file. How can I describe correct path in property file, if property file and xml file in the same dir?
Thanks.
The normal practice is to put those files in the runtime classpath or to add its root path to the runtime classpath. Then you'll be able to obtain the resource by ClassLoader#getResource() or as an InputStream by ClassLoader#getResourceAsStream().
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("filename.xml");
All you need to specify in the properties file would then be the full qualified name (the classpath location) of the XML file.
If you really insist in fiddling with disk file system paths like that, then you need to specify paths relative from the web content (the folder wherein /WEB-INF is located) and then use ServletContext#getResource() or ServletContext#getResourceAsStream() to obtain the resource. This however adds a ServletContext dependency on your code utilizing the XML file.

Categories

Resources