Log4j doesn't see .properties file - java

I use log4j for logging in my app. In every class I need to log something I have the following:
Properties props = new Properties();
try {
props.load(new FileInputStream("/log4j.properties"));
} catch (Exception e){
LOG.error(e);
}
PropertyConfigurator.configure(props);
log4j.properties is placed to the folder /src/main/resources/
the path /log4.properties is given by IDEA as copy reference. When I start my app it it shows the FileNotFoundException

Don't use FileInputStream.
The java.io and its consorts work with the current working directory i.e the directory from which the JVM is executed and not the code workspace.
to illustrate this consider the following piece of code
class ReadFrmFile {
public static void main(String args[]) {
FileInputStream fin = New FileInputStream("intemp.txt");
}
}
If the code is executed from C:\TEMP , the intemp.txt is expected to be in the working directory(C:/TEMP) in this case. If not this will throw the FileNotFoundException. The path of the file names are always absolute and not relative.
To avoid hardcoding the best way would be to place all the required files in the classpath and load them using getResourceAsStream().
Properties props = new Properties();
try {
InputStream inStream = **YOUR_CLASS_NAME**.class.getResourceAsStream("/log4j.properties");
props.load(inStream);
} catch (Exception e){
LOG.error(e);
}
PropertyConfigurator.configure(props);

log4j, by default, looks for the log4j.properties file in the classpath, so you don't need to use the class PropertyConfigurator, ony if the file doesn't exist in the root of the classpath.
In the Spring MVC + Log4j Integration Example, you will see:

Related

No such file or directory when reading Properties File in Java from one Class but not another

I am trying to read a properties folder from this path with respect to the repository root:
rest/src/main/resources/cognito.properties
I have a Class CognitoData from this path: rest/src/main/java/com/bitorb/admin/webapp/security/cognito/CognitoData.java which loads the Properties folder using this code, and it runs fine:
new CognitoProperties().loadProperties("rest/src/main/resources/cognito.properties");
#Slf4j
public class CognitoProperties {
public Properties loadProperties(String fileName) {
Properties cognitoProperties = new Properties();
try {
#Cleanup
FileInputStream fileInputStream = new FileInputStream(fileName);
cognitoProperties.load(fileInputStream);
} catch (IOException e) {
log.error("Error occured. Exception message was [" + e.getMessage() + "]");
}
return cognitoProperties;
}
}
However, when I call CognitoData from a test class located in rest/src/test/java/com/bitorb/admin/webapp/security/cognito/CognitoServiceTest.java , I get this error:
[rest/src/main/resources/cognito.properties (No such file or directory)]
Can anybody shed light on why this is happening?
File directory is not actually relative in that case. You need to provide appropriate file path for this. If you are already using spring boot, then
you can change your code to:
// this will read file from the resource folder.
InputStream inputStream = getClass().getClassLoader()
.getResourceAsStream("cognito.properties");
cognitoProperties.load(inputStream);
Otherwise you need to provide the full absolute path. new CognitoProperties().loadProperties("/absolutepath/..../cognito.properties")
I don't know what you're using for testing, but I suspect that the working directory when you run tests is not the project root.
One solution is to use an absolute path instead:
/absolute/path/to/project/rest/src/main/resources/cognito.properties
Or maybe check what is the working directory during testing and see if it can be changed to the project root.

Get "null" when I'm using getResourceAsStream to read properties file in Android Studio

I recently just start to using Android Studio for my programming study.
I've faced a problem today which is keep getting "null" when I using getResourceAsStream to read a properties file from JUNIT TEST.
I used to locate the .properties file under "src" directory when I was using Eclipse. But in Android Studio, it won't work.
Here is the code that part of a class called BeanFactory,:
private static Properties properties;
static {
properties = new Properties();
InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
try {
properties.load(is);
}catch (IOException e) {
e.printStackTrace();
}
}
In Eclipse, I located the the prop file under src, and it works just fine.
But in Android Studio, I've tried put the "bean.properties" file in several different directory. Such as /src, or/src/main/java, nothing worked out.
Where should I put the prop file? Is there any configurations that I should do for this?
Placing resources into assets is not acceptable in some cases. I solved this problem by packing required resourses into special jar file and placing this jar into libs directory.Thus you still can access them via standard Java technique.
There are two issues. In general resources are stored in a jar, with the compiled .class files.
getResource and getResourceAsStream are methods of a class. The resource is searched in the jar of this class (in general). So with inheritance getClass().getResource("...") might be dangerous.
The second, more grave pitfall is, that the path is relative to the package (directory) of the class, unless you use "/...".
Another way is to use ResourceBundle instead of Properties. ResourceBundle has a PropertiesResourceBundle for *.properties.
ResourceBundle properties = ResourceBundle.getBundle("bean");
try this:
1.put your own bean.properties file in app/src/main/assets
2.change you code to:
private static Properties prop;
static {
prop = new Properties();
try {
InputStream is = IWorkApplication.getInstance().getResources().getAssets().open("bean.properties", Context.MODE_PRIVATE);
prop.load(is);
} catch (IOException e) {
e.printStackTrace();
}
PS.IWorkApplication.getInstance() is define in my own application class.
Hope to be useful

Read relative static file in src

I have .tpl file containing some static content in a package in src.
e.g. src/A/B/C/test.tpl and i'm trying to read it from a class sibling that file (src/A/B/C/Test).
I can't find it in any way! FileReader throws FileNotFoundException.
SOLUTION: Class.getResource() works. Problem is about tpl extension which will not be compiled by default. IDEs have setting to add extensions to compile. I used .html instead of updating compiler settings.
Test.class.getResource("/A/B/C/test.html").getPath().replace("%20", " ")
You should use ClassLoader.html#getResourceAsStream
getClassloader().getResourceAsStream(resourcePath);
How about moving the file to src/main/resources and then trying something like -
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/test.tpl");
try {
context.getClassLoader().getResourceAsStream("test.tpl");
...
}
catch (IOException ex) {
ex.printStackTrace();
}

How to build jar using Eclipse "Export as jar option" with a properties file

public xFbConfigReader()
{
//props = new Properties();
propsdatabase = new Properties();
try
{
// load a properties file
InputStream dbin = getClass().getResourceAsStream("/properties/database.properties");
propsdatabase.load(dbin);
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
I keep My properties File named 'Database.properties' in a folder where the project is named 'Properties'.
When I do a Export as jar in Eclipse . The Properties Folder is visible.
But When I run the program it shows that there is a NUll point exception in dbin.
So which means I require the proper way to form a jar in Eclipse .Kindly suggest.
The better solution while handling properties file would be reading
static Properties databaseproperties= new Properties();
static {
try {
connectionProps.load(YourClassName.class.getClassLoader()
.getResourceAsStream("databaseproperties.properties"));
} catch (Exception e) {
System.out.println("Exception is " + e.getMessage());
}
}
This is better approch because
we can move our properties file to someother folder.
And infact we can keep properties folder out side of jar. say you can create
a folder called Configuration where you can include all the
properties files. As it is out side of jar you can change the
properties file when ever is required.
For change in properties
file no need to unjar it.
(OR) simply you can make this change no need to think about directory structure
Step 1: Move properties file to SRC
step 2: change this line as
follows
InputStream dbin = getClass().getResourceAsStream("/database.properties");
This is not much different from previous code as it is anyway stays inside the JAR file.
you are getting null pointer exception because properties file is not loaded try to use
FileInputStream to load the properties as follows
FileInputStream dbin = new FileInputStream("/properties/database.properties");
properties.load(dbin);

Where should I put my properties file for tests?

I have a properties file that I currently have in this folder:
/src/webapp/WEB-INF/classes/my.properties
I am loading it using:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream("/my.properties");
Properties props = new Properties();
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
}
String test = props.getProperty("test");
Now this works fine in my Spring mvc application.
But when I created a test for this, it fails and I am assuming because the way the application loads it is not using web-inf/classes since it is just a class and not a spring web app.
So where do I put my properties file so that when my junit tests run, the properties file is picked up?
Also, for my web app, what other folders are in the default class path other than /web-inf/classes ?
If you put my.properties under /src/test/resources in maven, it will be available as a normal resource to your tests.
I would remove the path (/) in classLoader.getResourceAsStream("/my.properties"); since the classloader starts in the root of the application. Keep the file in the same location as it is. Then change to
String filename = "my.properties";
InputStream is = classLoader.getResourceAsStream(filename); //for web-app
if(is == null)
is = new FileInputStream (filename); //for testing
Normally i put the property files directly in the src folder.

Categories