How to read properties file inside jar? - java

I have a config.properties file under the package com.abc.properties. From one of the java class present in com.abc.util, I need to read the property file. Both the files are present inside jar.
I have tried using
fs = new FileInputstream(VerifyFolderStructure.class.getResourceAsStream("com/abc/properties/config.properties"));
But it doesn't seem to work. Please help.
P.S: VerifyFolderStructure is my java class from which I need to load the properties file.

To obtain the stream you don't need FileInputStream at all. You can get the properties' file stream like this
InputStream is = VerifyFolderStructure.class.getResourceAsStream("/com/abc/properties/config.properties");

I think you need to add "/" in the front of you path.if you don't add "/" that means the properties is located in the same packages path as VerifyFolderStructure class.

Related

How to not hard-code a file path

I'd like to calculate the path of a file placed into Source Packages using this implementation:
URL pathSource = this.getClass().getResource("saveItem.xml");
When I try to create a new File like the code below:
File xmlFile = new File(pathSource.toString());
And I try to use it to create a document like this:
Document document = builder.parse(xmlFile);
This give me the java.io.FileNotFoundException.
How can I calculate the file path without hard-coding?
PS: I already used pathSource.getPath() but it doesn't work either.
I would like to use a similar implementation:
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
PPS: The structure is the following:
You can't access a resource that inside a JAR file as a File instance. You can only get an InputStream to it.
As such, the following line
File xmlFile = new File(pathSource.toString());
won't work properly and when an attempt is made to read it later, a FileNotFoundException will be thrown.
Assuming you're trying to parse a XML file using DocumentBuilder, you can use the parse(InputStream) method:
try (InputStream stream = this.getClass().getResourceAsStream("saveItem.xml")) {
Document document = builder.parse(stream);
}
Short answer - saveItem.xml is not in the classpath.
If it is a web application, then file may be added to WEB-INF/classes folder.
Edit:
Try this.getClass().getResourceAsStream() too.
getClass().getResource("saveItem.xml");
looks for the file in the same package (which are directories when you look at the file system) as the class that getClass() returns.
Make sure the file is in there. Also make sure it's really in there when you run your code, there's a difference between your source folder and the target or bin folder where the compiled class files are placed.
Also check what pathSource.toString() contains.

How to read the property file from a class file packed as a same jar

I want to read a property file from a java class file which the both are packed together as a same jar.
Project Structure:
src
--->com
------->xyz
----------->Property(foldername)
-------------------------------------->abc.properties
----------->JavaClassFileFolder
-------------------------------------->a.java
In the above structure folder, i want to read a abc.properties file from a.java file. I tried below methods in a.java file to read.
Method1:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("com/xyz/Property/abc.properties");
Properties prop = new Properties();
prop.load(in);
Result: Throws NPE at prop.load(in)
Method 2:
ClassLoader cl = Constants.class.getClassLoader();
Properties prop = new Properties();
prop .load(cl.getResourceAsStream("com/xyz/Property/abc.properties"));
Result: Throws NPE at prop.load(in)
It should work. The only reason it wouldn't is that com/xyz/Property/abc.properties is not in the jar
Start the path with a /, see this.getClass().getClassLoader().getResource("...") and NullPointerException.
That said:
If you use Maven, put your property files to src/main/resources/com/xyz/property. Maven will do the necessary copying for you.
Always begin your Java package names with a lower case letter, i.e. use property instead of Property. Normally, you expect only Java classes to begin with a capital letter.
Usually, it is not necessary to work with the classloader, use Constants.class.getResourceAsStream("/com/xyz/property/abc.properties") instead.
your method one has to work as far as this refers to class a and properties file is present at the destination you mentioned
You are using a relative path (no / at the beginning), therefore getResourceAsStream starts from the package of your Object (this). Add the / at the beginning and you are searching classpath absolute and because you are in the same Classloader (your Class and your Property - File are in the same jar) here are no issues as well.
There might be an exception thrown while trying to read the InputStream object value. Try using a throws IOException class.

Create a java file inside a package

Currently, my plugin creates a java file in my project(IProject). But I want that java file within a specified Package. How to do it.
IFile sampleFile = parentFolder.getFile("Sample.java");
if(!sampleFile.exists()) FileInputStream fileStream = new FileInputStream("C:\Users\Uma\Desktop\treasureHunt\Application.java"); sampleFile.create(fileStream, false, null);
This is my current piece of code.
How can I create the sampleFile within a package. For example: in package com.mdh.se as com.mdh.se.Sample.java
If you have a "package" (e.g. "com.mdh.se") then you'll have a corresponding subdirectory (for example, "c:\users\uma\desktop\treasurehunt\com\mdh\se"). Simply write your file there.
I think, that the only thing you need to do is to create folders representing your package structure. So your path should look like C:\Users\Uma\Desktop\treasureHunt\com\mdh\se\Sample.java for your example.
You can get a special file inside the package by calling
java.net.URL imgURL = ResourceManager.class.getResource( "ResourceManager.class" );
From these URL you can extract the directory, the file is placed.
A new file you can create with
new File(directory,filename);

Is there any way to change a properties file that is in my classpath?

I have a properties file that is in my classpath. My requirement is to change some properties in this file based on some inputs I get from arguments. The nature of arguments decide whether I need to change the properties and if yes which properties to change. The problem is that all classpath entries are loaded at the application startup time, so changing from within my application would not have any effect. How do I overcome this problem?
One possible solution I can think of is to not add this properties file in classpath but add after modifications are done. Is it viable? What can be a good solution?
It doesn't matter whether this file is on your classpath or not. It is a file: if you overwrite its contents, it will have changed. There isn't some in-memory copy that magically gets made at startup. This is very different from classes that are loaded in and which might need change at runtime.
Properties files that adhere to the right format can be read into a java.util.Properties object. You could do that, use the object to alter the properties as needed, then write it back out to the file. Check the store and load methods in that class. Mind that if you use the versions that take an Output/InputStream, the encoding is hard-coded. If the file's encoding is anything else than ISO-8859-1, use a method with an appropriate Writer/Reader.
Depends on how your application is deployed. If your properties files is inside a jar, you won't be able to directly change that properties file since its packaged and zipped up in an archive. You can instead as someone else mentioned load those properties into an object, and then store/write out to an external location, probably a URL based location. URL is convenient because it gets you access to virtually any location and it has that nifty openStream() method for loading properties. Your application could then look for the new file on load, and default to the application startup version if it fails to read/load from the new location.
Here is a sample code:
Properties p = new Properties();
File f = new File("file");
InputStream in = new FileInputStream(f);
p.load(in);
p.put("key", "blah");
OutputStream out = new FileOutputStream(f);
// If no comments p.store(writer);
p.store(out, "properties");
You need to first remove that property from the property file and then re-define it. Their is no way to directly modify the properties file.
Below is an example:
Properties pproperties = new Properties();
if (properties.containsKey("key1")) {
properties.remove("key1");
properties.setProperty("key1", "value1");
properties.store(new FileOutputStream("file.properties"), null);
}

Storing changes in .properties file that has been read via getClass().getResourceAsStream

I am writing a java web application that reads properties from a .properties file. Since I do not know the absolute path of the .properties file, because it depends on the environment the application will run on in the future, I have to load it with "getClass().getResourceAsStream":
Properties props = new Properties();
props.load(getClass().getResourceAsStream("test.properties"));
message = props.getProperty("testdata");
This works as expected. Now I want to change the value for testdata in the file. But I cannot open an Outputstream to write to, because I still don't know the path of the .properties file.
props.setProperty("testdata", "foooo");
props.store(new FileOutputStream("?????"), null);
Is there a way to get the path of the file or can I use the established Properties-object somehow? Any ideas are welcome that allow me to change the .properties file.
You can get an URL by using getResource() rather than using getResourceAsStream()
You can then use that URL to read from and write to your properties file.
File myProps = new File(myUrl.toURI());
FileInputStream in = new FileInputStream(myProps);
Etc.
The Properties class includes a store method that can be used to save the properties back to the stream that was read in getClass().getResourceAsStream("test.properties").

Categories

Resources