How to edit file in resources of Spring MVC? - java

I have a project on Spring MVC, The resources folder added to buildpath of Spring.
Project Structure
On some UI action i want to edit the file resources/thirdparty/thirdparty.er from the controller.
So here are the code is tried
File inputFile = new File("/home/local/<User>/Desktop/workspace/<ProjectName>/WebContent/resources/thirdparty/thirdparty.er");
result - it worked fine
Instead of absolute path i wanted a relative path so i tried
File inputFile = new File("../../<something>/WebContent/resources/thirdparty/thirdparty.er");
result - it worked fine, but the path was relative to eclipse(base path), as i was executing code in eclipse
To remove eclipse path dependency, i tried
File inputFile = new File("/resources/thirdparty/thirdparty.er");
result - it didnot worked
Later on searching web, i found
Resource resource = new ClassPathResource("/thirdparty/thirdparty.ER");
File inputFile = resource.getFile();
result - it is returning
/home/local//Desktop/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps//WEB-INF/classes/thirdparty/thirdparty.er
which actually isn't the file i want to edit.
Please let me know how this can be done. I donot want any path dependencies on eclipse, server or the system, it sould be completely based on project.

Maybe all you need is
Resource resource = resourceLoader.getResource("classpath:/thirdparty/thirdparty.ER");
and just autowire the resource loader like that:
#Autowired
private ResourceLoader resourceLoader;

Related

Spring boot: trying to read directory content inside resources folder produces FileNotFoundException when reading from jar

so I have a problem with Spring-boot. Basically the idea is that in resources i have a directory called migrations which stores sql scripts that needs to be launched. It works well on local machine. But, as soon as I upload project to server i get greeted with error of:
Caused by: java.io.FileNotFoundException: class path resource [migrations] cannot be resolved to absolute file path because it does not reside in the file system:
A lot of googling helped me to identify problem. It has to do with file being in .jar, when I do read directory as InputStream, as stated in other issues like this one, I can get specific file and access it's scripts if I specify full name of that resource, like
resourceLoader.getResource("classpath:migrations/file.sql")
But, specifying full name of resource like that and defining all the file names is not an option, since in the future this folder can expand a lot and i don't want to manually edit code to add file to running.
Is there any workaround for this issue that would allow me to at least read file names from directory and then access them one by one?
i don't think there is a good solution for that if it deploy has a jar unless you use docker file to copy the resource and deploy it. getInputStream() was always the best solution to get file from anywhere.
maybe this solution but not try yet
ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
Resource[] resources = resolver.getResources("classpath*:/*.sql") ;
for (Resource resource: resources){
do your things maybe print the name resource
}

ClassPathXmlApplicationContext error, Spring framework

I have encountered a problem when it comes to the Springs framework, which leads to that the communication between the server and the database does not work.
The project that I created is a Spring project, then refactored to Maven.
At this line in the code:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("projectName/spring.xml");
I get this error:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [projectName/spring.xml]; nested exception is java.io.FileNotFoundException: class path resource [projectName/spring.xml] cannot be opened because it does not exist
But it does exist. And I've tried solutions for this problem such as writing ClassPathXmlApplicationContext("spring.xml") instead. This doesn't help however, since then Spring automatically looks in the folder src/main/resources. This doesn't work for me since my project structure doesn't allow me to add this folder and put a XML-file in it. If I try to create this folder, then it is automatically put inside the Java-resources folder, and Eclipse won't allow me to put XML in there.
This is how my project looks:
enter image description here
Is there a way for me to declare where Spring should look for this spring.xml-file?
The ClassPathXmlApplicationContext assumes that the file is on your classpath (Javy describes how to do load a resource from your classpath).
If you want to load the configuration from your file system (as you're doing), you might want to consider using FileSystemXmlApplicationContext instead. Using this mechanism to load your context you can pass a file system location as you're currently doing.
new ClassPathXmlApplicationContext(this.getClass().getResource("/spring.xml").getPath())
try the code above
hope that helped
Spring doesn't look at the src/main/resources, it looks at the classpath.
If you write projectName/spring.xml you need to have this file in bin/projectName/spring.xml or build/projectName/spring.xml. Where bin or build your build folder.
If you build a jar, this file should be in the jar!projectName/spring.xml.
For the web-application this file should be in the WEB-INF/classes/projectName/spring.xml.
If you add src/main/resources at the class path, then content of this folder will be in the build folder. Maven adds src/main/resources at the class path automatically.
Sometimes you should rebuild (clean) your project in the IDE to have such files in the build folder.
Use "FileSystemXmlApplicationContext" as
ApplicationContext context = new FileSystemXmlApplicationContext("spring.xml");

FileInputStream in Spring MVC fails to find file

I am working on a SpringMVC project which runs a number of automated tests on a database. The access details for this database are located in a .properties file. This file is located within the project directory.
FileInputStream fis = new FileInputStream("batch-dm.properties");
propFile = new Properties();
propFile.load(fis);
As the file is stored in the project directory the FileInputStream should be able to access it no?
If I provide the absolute path e.g.
FileInputStream fis = new FileInputStream("C:/workspace/Project/batch-dm.properties");
It recognises the file and runs properly.
Do I need to sore this file in a different location because it is a Spring MVC project?
Thanks
Just to clear out your mind, try to see what is the value that outputs System.getProperty("user.dir") (let's call it A), this will print the complete absolute path from where your application was initialized, more specifically it will print the directory from where the JVM was started.
If you doesn't supply a parent path to the file that you are trying to open, the (A) path is taken by default and the file is looked inside that directory. So please, have in mind that.
Aditional information
If you absolutely need that file you should include it in your project so you can access it as a resource. Resource is a file that is included in your project and came bundled with the generated .jar or .war for re distribution.
My advice is to put the file in the package and use as a resource as it the safer way to work with external resources that should be shipped with your project.
Take a deeper look at this post for more about practical way of handling resources.
Please refer below link:
https://stackoverflow.com/a/2308388/1358551
You may have to use getResourceAsStream().

How to load property file located inside jar file

How to load property files placed in resource folder of an executable jar file. Here my app itself is a jar and it executes on it own. It need to find this property file (placed within itself under resource folder) at runtime depending on the path mentioned in the code. I have used below two methods but it didn't help me. Point here is, both these options are working fine when i execute in eclipse, but doesn't work when I pack it into an executable jar. It throws NullPointerException. Only problem I see here is that jar is not able to pick the property files with given path. Any help would be appreciated.
Method 1: Using Apache Commons Configuration
URL propFileURL = XYZ.class.getClassLoader().getResource("/config.properties");
Configuration propertyConfiguration = null;
propertyConfiguration = new PropertiesConfiguration(propFileURL);
In above case I'm getting ConfigurationException. Class is not able to find file mentioned in given path.
Method 2: Using getResourceAsStream. I know that getResource doesn't work if we are to load files from network on in any other location.
InputStream is =XYZ.class.getClassLoader().getResourceAsStream("/config.properties");
Properties prop = new Properties();
prop.load(is);
In this case, I'm getting nullPointerException.
Let me know if you need more details.
jar content Heirarchy
Properties file - /java-file-io-application/src/main/resources/config.properties
XYZ class - /java-file-io-application/src/main/java/org/bc/xyz/iplugin/utilities/XYZ.java
Looks like you might be building your jar incorrectly. Files from 'src/main/resources' would be expected at the root of the jar file. If your jar file contains the 'src/main/resources' directory, something's off with your build.

Spring - Loading a folder from project structure as a directory?

I have written an application using Spring. I have a package called "Services" that has a "Resources" folder. In that folder are a text file (file.txt) and a folder (write). I have managed to load the text file using the following lines of code:
URL file = this.getClass().getResource("/file.txt");
File myFile = new File(file.getFile())
However I am having opening the folder. The following does not seem to work:
URL folder = this.getClass().getResource("/write");
Running the line about throws a NullPointerException. Can anyone suggest ways in which I can accomplish this task?
I believe you need to end your string with "/". The following may work:
URL folder = this.getClass().getResource("/write/");

Categories