A property file in project classpath.

config.properties

#config file
json.filepath = /Users/mkyong/Documents/workspace/SnakeCrawler/data/

1. Non Static Method

Normally, you can access above properties file via getClass().getClassLoader().getResourceAsStream.


package com.mkyong.crawler.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class FileHelper {
	
  public String getFilePathToSave() {

	Properties prop = new Properties();
	String filePath = "";

	try {

	  InputStream inputStream = 
	    getClass().getClassLoader().getResourceAsStream("config.properties");
				
	  prop.load(inputStream);
	  filePath = prop.getProperty("json.filepath");
		
        } catch (IOException e) {
		e.printStackTrace();
	}

	return filePath;

  }

}

Run it.


FileHelper helper = new FileHelper();		
String filePath = helper.getFilePathToSave();

2. Static Method

If the method getFilePathToSave() is converted to static method, the getClass() method will be failed, and prompts “Cannot make a static reference to the non-static method getClass() from the type Object“.

Instead, you should use CurrentClass.class.getClassLoader().getResourceAsStream.


package com.mkyong.crawler.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class FileHelper {
	
  public static String getFilePathToSave() {

	Properties prop = new Properties();
	String filePath = "";

	try {

	  InputStream inputStream = 
	    FileHelper.class.getClassLoader().getResourceAsStream("config.properties");

	  prop.load(inputStream);
	  filePath = prop.getProperty("json.filepath");
		
	} catch (IOException e) {
		e.printStackTrace();
	}

	return filePath;

  }

}
	
String filePath = FileHelper.getFilePathToSave();

References

  1. Dzone – Loading A Property File From The Classpath
  2. Java ClassLoader JavaDoc