properties file is not called while creating the jar - java

I have created a java project in which I am using a properties file also which is created inside a java packgae named abcedf
so package name is abcdef which consists a class name abc.java and a property file named drg.properties ,now from class abc.java i am referring to that properties file as..
abc tt = new abc();
URL url = tt.getClass().getResource("./drg.properties");
File file = new File(url.getPath());
FileInputStream fileInput = new FileInputStream(file);
now this file is referred and my program runs successfully but when I am trying to make it executable jar then this property file is not referred
please advise what is went wrong while creating the property file.

Use
tt.getClass().getResourceAsStream("./drg.properties");
to access the property file inside a JAR. You will get an InputStream as returned object.
-------------------------------------------------
Here is an example to load the InputStream to Properties object
InputStream in = tt.getClass().getResourceAsStream("./drg.properties");
Properties properties = new Properties();
properties.load(in); // Loads content into properties object
in.close();
If your case, you can directly use, the InputStream instead of using FileInputStream

When you access "jarred" resource you can't access it directly as you access a resource on your HDD with new File() (because resource doesn't live uncompressed on your drive) but you have to access resource (stored in your application jar) using Class.getResourceAsStream()
Code will looks like (with java7 try-with-resource feature)
Properties p = new Properties();
try(InputStream is = tt.getClass().getResourceAsStream("./drg.properties")) {
p.load(is); // Loads content into p object
}

Related

How to create a json file inside the resource folder in SpringBoot?

I want to write into a json file inside the resource folder of springboot. So I wanted to check, how to create a file and insert data. If file exists after creation then add the data into file, else create file and add data.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
FileOutputStream fileOutputStream = new FileOutputStream(new
File(classLoader.getResourceAsStream("/Response.json").toString()));
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8);
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
try {
for(list){}
string result="user Should be active user";
writer.write(String.valueOf(result));
writer.close();
} catch{}
IMHO, If you're using docker or any container to deploy the apps, just let the code to write on the root folder (home where app.jar deployed), coz in the runtime actually the metadata will not accessible since it already bundled on the jar by spring-boot.

The filename, directory name, or volume label syntax is incorrect - how to specify file path in properties file

I am reading properties file to get a file path as below.
String result = "";
InputStream inputStream = null;
try {
Properties prop = new Properties();
String propFileName = "config.properties";
inputStream = GetPropertyValues.class.getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
The properties file has the path specified like below.
configSettingsFilePath = C:\\\\ConfigSetting.xml
Now I get this below exception when I run my code saying file is not found.
Creating instance of bean 'configSettingHelper'
configSettingsFilePath = C:\ConfigSetting.xml
2017-09-18 14:47:00 DEBUG ConfigSettingHelper:42 - ConfigSettingHelper :: ConfigSetting File:configSettingsFilePath = C:\ConfigSetting.xml
javax.xml.bind.UnmarshalException
- with linked exception:
[java.io.FileNotFoundException: C:\Java\eclipse\eclipse\configSettingsFilePath = C:\ConfigSetting.xml (The filename, directory name, or volume label syntax is incorrect)]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
Instead of reading the path from properties file, if I directly use "C:\ConfigSetting.xml" in the code, it reads the file.
Can you please suggest what I should use in the properties file to specify the path?
Reading the file only fails when the .jar is running.
Running the app from within Netbeans is fine. (Different path)
Also, the path is coming from
URL resourceURL = MyClass.class.getResource("mydir/myfile.txt");
Printing out the path is perfect.
Also, a mypicture.gif in the very same directory loads fine:
ImageIcon mypicture = new ImageIcon(imageURL, description)).getImage();
even when running the .jar. IE: the actual path must be fine.
It is only a text file I try reading via
InputStream input = new FileInputStream(fileName);
is when it fails - and only if it is in the jar.
This is probably because C:\ is not on the classpath. You're using getClassLoader() which presumably returns a ClassLoader.
According to the docs for ClassLoader#getResource:
This method will first search the parent class loader for the
resource; if the parent is null the path of the class loader built-in
to the virtual machine is searched. That failing, this method will
invoke findResource(String) to find the resource.
That file is in the root of the drive, which is not going to be on the classpath or the path of the class loader built-in to the VM. If those fail, findResource is the fallback. It's unknown where findResource looks without seeing the implementation, but it doesn't appear to pay attention to the C:.
The solution is to move the properties file into your classpath. Typically, you'd put property files like this in the src/main/resources folder.

Not able to load the properties file into a java file

I am not able to load the properties file into a java file. getting file not found exception. Can you please help here.
Java file location:
classes/com/my/location/for/javabased/utilities/convertor/servlet/GetProp.java
Properties file location:
classes/com/my/property/properties/Config.properties
My code:
Properties inputParams = new Properties();
FileInputStream in = new FileInputStream("classes/com/my/property/properties/Config.properties");
inputParams.load(in);
in.close();
Getting File not found exception
I prefer reading the property file in class like this
public class SomeClass{
private static Properties someProperties = new Properties();
static{
someProperties.load(SomeClass.class.getResourceAsStream("/com/my/property/properties/Config.properties"));
}
Hope this helps.
The java class File (which is used by FileInputStream) is based on the file system path, either absolute, or relative to the current working directory. Both is mostly not under full control of the running application. If your resources can be found within the classpath (which from the point of view of the running application is always the same) you should use the resource loading mechanisme of your classloader (as Vijendra Kulhade pointed out in his answer).

correct way to read properties file

I am having trouble finding out the right way to load a properties file.
The structure is : Inside src/com.training , I have my class and the properties file as well. I have to read it using the absolute path as shown in the code below to get it to work:
Properties prop = new Properties();
InputStream input = null;
input = new FileInputStream("D:/Dev/workspace/Training/src/com/training/consolemessages.properties");
prop.load(input);
System.out.print(prop.getProperty("INITIAL_MESSAGE"));
How can I use the relative path to work in this code for accessing the properties file. The properties file and the class which is accessing are both at the same level '/src/com.training'
You could put your properties files into src/resources folder, and fetch them on classpath.
You could do something like this:
ResourceBundle bundle = ResourceBundle.getBundle("resources/consolemessages");
System.out.println(bundle.getString("INITIAL_MESSAGE"));
When using ResourceBundle, Locale support is also easy to implement, should you need to have language specific properties.

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