Ajinkya
Ajinkya

Reputation: 22710

Read the values from properties file

I have created a dynamic web project in Eclipse and have written a simple code to read from properties file.
Here is my code

public class AutocompleteService {

public static void main (String args[])
{
  Properties properties = new Properties(); 
  properties.load(new FileInputStream("autocomplete.properties"));
  System.out.println("Test : " + properties.getProperty("test"));   
}  

When I run this I got file not found exception.

java.io.FileNotFoundException: autocomplete.properties (The system cannot find the file specified)

My package structure is as below

-src
 - com.serive (package)
   - AutocompleteService.java
   - autocomplete.properties   

Both AutocompleteService.java and autocomplete.properties are in same package i.e. com.service.Do we need to anything else to read from properties file ?

Ref: http://www.exampledepot.com/egs/java.util/Props.html

~Ajinkya.

Upvotes: 2

Views: 9049

Answers (5)

djna
djna

Reputation: 55897

Your code is looking in the "current directory" when the application is run.

Use Class.getResourceAsStream() to read from the same place as the classes.

Upvotes: 2

Alex Objelean
Alex Objelean

Reputation: 4133

Get the stream relative to your class:

AutocompleteService.class.getResourceAsStream("autocomplete.properties")

Upvotes: 5

Bohemian
Bohemian

Reputation: 424973

The "current" directory is where you started the server from, so refer to your file relative to that, eg "config/autocomplete.properties" or wherever you like.

The best approach is to know what the problem is. Use code like this that helps you debug the problem:

File propertiesFile = new File("config/autocomplete.properties");
if (!propertiesFile.exists())
    throw new IllegalStateException("Could not find properties file: " + propertiesFile.getAbsolutePath());
properties.load(new FileInputStream(file));

If this explodes, the exception message will show you where it thinks the file is, and yo'll quickly figure out how to correct the problem.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691635

Creating an input stream using a relative path will try to open a file in the current directory of the running program. In your case, the current directory is the directory of execution of your servlet container (Tomcat, Jetty, etc.)

What you want to do is to open a properties file which is located along with your classes, in the war file. This properties file should thus be laoded by the class loader, and using Class.getResourceAsStream() is the appropriate way. Look at the linked javadoc to understand which kind of path to supply as argument.

Upvotes: 0

epoch
epoch

Reputation: 16595

you have to load this from the classpath: ex

ClassLoader loader = Thread.currentThread().getContextClassLoader();
stream = loader.getResourceAsStream(fileName);

When you have the stream you can pass it to properties.load()

Upvotes: 7

Related Questions