Question

I have a file mydoc.txt at the following location

C:/Tomcat6.0/webapps/myapp/WEB-INF/classes/document/mydoc.txt

I have to get this file location through constructor injection and read the file.

public DocumentReader(String path) throws IOException, FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
  stringBuilder.append(line);
}
String doc = stringBuilder.toString();
}

I have configured the file location in applicationContext.xml as shown below.

<bean id="DocumentReader" class="com.myapp.DocumentReader" >
<constructor-arg  value="classpath:document/mydoc.txt"></constructor-arg>
</bean>

But, I am getting FileNotFound Exception while running the application. Is there any other way to read the file from this location ?

Exception

java.io.FileNotFoundException:  classpath:document\mydoc.txt(The filename, directory name, or volume label syntax is incorrect)
Was it helpful?

Solution

Change your constructor to take org.springframework.core.io.Resource instead of String.

If your constructor-argument is of type String, Spring inserts the value just like you wrote it down. Your FileReader then looks for a file named mydoc.txt in the folder classpath:document (which on some operating systems - like windows - is not even a valid folder-name)

If your constructor-argument is of type Ressource, Spring assumes that the String you are injecting is a Spring-Ressource-Path and resolves that for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top