Java Spring - How to use classpath to specify a file location? - java

How can I use the classpath to specify the location of a file that is within my Spring project?
This is what I have currently:
FileReader fr = new FileReader("C:\\Users\\Corey\\Desktop\\storedProcedures.sql");
This is hardcoded to my Desktop. What I would like is to be able to use the path to the file that is in my project.
FileReader fr = new FileReader("/src/main/resources/storedProcedures.sql");
Any suggestions?

Are we talking about standard java.io.FileReader? Won't work, but it's not hard without it.
/src/main/resources maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:
InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");
If the result is not null (resource not found), feel free to wrap it in a reader:
Reader reader = new InputStreamReader(is);

From an answer of #NimChimpsky in similar question:
Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();
Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).
Note that Resource have a method to get a java.io.File so you can also use:
Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean
<bean class="test.Test1">
<property name="path" value="classpath:/test/test1.xml" />
</bean>
and you get it in your bean as Resource:
public void setPath(Resource path) throws IOException {
File file = path.getFile();
System.out.println(file);
}
output
D:\workspace1\spring\target\test-classes\test\test1.xml
Now you can use it in new FileReader(file)

looks like you have maven project and so resources are in classpath by
go for
getClass().getResource("classpath:storedProcedures.sql")

Related

writing to file in maven project

Hi i am using maven web project and want to write something to file abc.properties. This file in placed in standard /src/main/resource folder. My code is:
FileWriter file = new FileWriter("./src/main/resources/abc.properties");
try {
file.write("hi i am good");
} catch (IOException e) {
e.printStackTrace();
} finally {
file.flush();
file.close();
}
But it does not work as path is not correct. I tried many other examples but was unable to give path of this file.
Can you kindly help me in setting path of file which is placed in resources folder.
Thanks
I think you're confusing buildtime and runtime. During buildtime you have your src/main/java, src/main/resources and src/main/webapp, but during runtime these are all bundled in a war-file. This means there's no such thing as src/main/resources anymore.
The easiest way is to write to a [tempFile][1] and write to that file. The best way is to configure your outputFile, for instance in the wqeb.xml.
[1]: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#createTempFile(java.lang.String, java.lang.String)
If your file is dropped under src/main/resources, it will end up under your-webapp/WEB-INF/classes directory if you project is package as a Web application i.e. with maven-war-plugin.
At runtime, if you want to files that are located under the latter directory, which are considered as web application resources, thus are already present in the application classpath, you can use the getResourceAsStream() method either on the ServletContext or using the current class ClassLoader:
From current thread context:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream("abc.properties");
FileWriter file = new FileWriter(new File(new FileInputStream(is)));
// some funny stuff goes here
If you have access to the Servlet context:
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/abc.properties");
FileWriter file = new FileWriter(new File(new FileInputStream(is)));
// some funny stuff goes here
Notice the leading slash in the latter example.

How to link a local file

I'm trying to use a local file in which I've specified my db connection properties which is named dao.properties. And I'm proceeding this way:
InputStream fichierProperties = classLoader.getResourceAsStream( "/src/dao/dao.properties" );
However, when using this path, I'm getting an exception stating that the debugger wasn't able to find that file.
Here are some packages in my project:
The dao.properties is just under the dao package.
How do I resolve this, please?
If you put the file inside the src folder, the IDE probably is packaging, when instructed to compile and build, the file into the bundled generated jar. So you can reach with the method GetResourceAsStream.
So if you put the file (dao.properties) in root folder of your sources files (generally the src folder), just simple referring to dao.properties will refer to the resource.
If you put the file inside a subfolder of src, the correct way to reference it would be subfolder/dao.properties.
The first "/" is not necessary as the getResourceAsStream always search in the classpath, that for default is the root of the sources folder, inside the jar. (where are not talking about external files!)
Updated:
Assuming you place a file name notes.txt inside a folder(package) named ´sub´, this is valid example, only for purporses of how to get a bundled file that is in jar.
public class Main {
public static void main (String[] args) throws IOException {
InputStream is = Main.class.getResourceAsStream("sub/notes.txt");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
while (s != null) {
System.out.println (s);
s = br.readLine();
}
is.close();
}
}
I add more information about this, by referring to this post

Can't read in pom.xml file from webapp

So my tomcat webapps directory looks like this:
C:/tomcat/webapps/myApp/
myApp/
resources/...
META-INF/
MANIFEST.MF
maven/
my.package.name/
myApp/
pom.properties
pom.xml
WEB-INF/
classes/...
lib/...
web.xml
I have an AppConfig.java (java spring config) where I am trying to get the pom.xml file so I can get certain things out of it. I have tried many things but have been unsuccessful in getting the file. I have a bean that I have just been putting a breakpoint in and trying different things to get the file.
#Bean
public String clientVersion()
{
BufferedReader reader = new BufferedReader(new InputStreamReader(ClassLoader.class.getResourceAsStream("/pom.xml")));
return "";
}
I have tried ClassLoader.class.getResourceAsStream() with many different paths though from what I have been able to find in other posts and forums ClassLoader.class.getResourceAsStream("META-INF/maven/my.package.name/myApp/pom.xml") should work, but I get null no matter what I do. Any suggestions?
To load resource you have to provide full path not only filename. Eg /maven/mypackage/myapp/pom.xml
Try with opening stash.
Change the code to:
#Bean
public String clientVersion()
{
BufferedReader reader = new BufferedReader(new InputStreamReader(ClassLoader.class.getResourceAsStream("/META-INF/maven/my.package.name/myApp/pom.xml")));
return "";
}
Depending on how it's stored on you file system, the my.package.name might need to actually be my/package/name.
Don't use the ClassLoader class, because you're probably picking up the wrong classloader (confusing, right?!).
Instead use my.package.name.MyClass.class.getResourceAsStream("/META-INF/maven/my.package.name/myApp/pom.xml")));, this way you can ensure both files (the class and the pom.xml) are available with the same classloader, since the are in the same archive.
I do this to get it as a String (inside a class called ServerResource.java, so swap in your class name):
InputStream is = ServerResource.class.getResourceAsStream("/META-INF/maven/org.buffalo/platform/pom.xml");
String pom = getStringFromInputStream(is);
if you extract your war/jar, you can confirm the path to the pom (for me it's META-INF/maven/org.buffalo/platform_ws/pom.xml)
Class::getResourceAsStream loads resources from the classpath; in a web application, that means files inside WEB-INF/classes, or inside one of the JAR files inside WEB-INF/lib. Your POM file isn't in either of those places, so it's not on the classpath.
Rather, being somewhere under the WAR root, it's a web resource, rather than a classpath resource. You can load web resources using ServletContext::getResourceAsStream.
Your code should look like:
#Bean
public String clientVersion(ServletContext servletContext) throws IOException {
String pomPath = "/META-INF/maven/my.package.name/myApp/pom.xml";
try (InputStream pomStream = servletContext.getResourceAsStream(pomPath)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(pomStream));
return "";
}
}

Spring MVC Read and Parse a file in

I'm new to Spring and I'm just trying to open a simple text file and parse it so I can create some POJOs. My problem is I can't get Spring to find the txt file.
I've tried putting the file all over the place and right now I've put it in
/myAop/src/main/resources/myFile.txt
and I'm referencing it in a file called
com.myApp.pojo.Team.java
using code like this:
FileSystemResource resource = new FileSystemResource("/myApp/src/main/resources/myFile.txt");
File f =resource.getFile();
However, I'm not having any luck.
I've also tried several other locations.
Thanks in advance for the help.
You need to specify file name only as src/main/resource is already in classpath.
Try this:
FileSystemResource resource = new FileSystemResource("myFile.txt");
File f =resource.getFile();
Try
New Xmlclasspathresource() .
Try anothe path
FileSystemResource resource = new FileSystemResource("/main/resources/myFile.txt");
Actually the file from resources is placed under classes.
Try using absolute path
FileSystemResource resource = new FileSystemResource("file:C:/test/workspace/src/myApp/src/main/resources/myFile.txt");
You may use classpath as well, but the file should be in the classpath.
FileSystemResource resource = new FileSystemResource("classpath:myApp/src/main/resources/myFile.txt");
What I wound up doing was putting the file in base directory with the POM.xml file and then i could get to it just by using the name and not by having to use any kind of path. I'm sure there are better ways but for the time being I just needed to move on.

Not able to load properties file in Java

I am trying to load a properties file. The properites file is in the class path of the application.
Properties p = new Properties();
p.load(new FileInputStream("classpath:mail.properties"));
System.out.println(p.get("hi"));
Now I say classpath, because another file called x.properties is referred in an xml file like this
<property name="x">
<util:properties location="classpath:x.properties" />
</property>
I placed my mail.properties in the same folder as x.properties, but my Java program is not able to find it ? Any idea what I am missing ?
Just because some program processing that XML file likes the syntax classpath:x.properties doesn't mean that it is a universally accepted syntax in Java!
If you provide "classpath:x.properties" to a FileInputStream it will look for a file named classpath:x.properties. (Check the documentation of that particular constructor.)
Try providing the full path to that file. If the file happens to be on your class path, you could use something like
p.load(getClass().getResourceAsStream("mail.properties"));
if mail.properties is indeed on your classpath, you will have better luck loading it via a class loader:
Properties p = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("mail.properties");
p.load(is);

Categories