Read maven.properties file inside jar/war file - java

Is there a way to read the content of a file (maven.properties) inside a jar/war file with Java? I need to read the file from disk, when it's not used (in memory). Any advise on how to do this?
Regards,
Johan-Kees

String path = "META-INF/maven/pom.properties";
Properties prop = new Properties();
InputStream in = ClassLoader.getSystemResourceAsStream(path );
try {
prop.load(in);
}
catch (Exception e) {
} finally {
try { in.close(); }
catch (Exception ex){}
}
System.out.println("maven properties " + prop);

One thing first: technically, it's not a file. The JAR / WAR is a file, what you are looking for is an entry within an archive (AKA a resource).
And because it's not a file, you will need to get it as an InputStream
If the JAR / WAR is on the
classpath, you can do SomeClass.class.getResourceAsStream("/path/from/the/jar/to/maven.properties"), where SomeClass is any class inside that JAR / WAR
// these are equivalent:
SomeClass.class.getResourceAsStream("/abc/def");
SomeClass.class.getClassLoader().getResourceAsStream("abc/def");
// note the missing slash in the second version
If not, you will have to read the JAR / WAR like this:
JarFile jarFile = new JarFile(file);
InputStream inputStream =
jarFile.getInputStream(jarFile.getEntry("path/to/maven.properties"));
Now you probably want to load the InputStream into a Properties object:
Properties props = new Properties();
// or: Properties props = System.getProperties();
props.load(inputStream);
Or you can read the InputStream to a String. This is much easier if you use a library like
Apache Commons / IO
String str = IOUtils.toString(inputStream)
Google Guava
String str = CharStreams.toString(new InputStreamReader(inputStream));

This is definitely possible although without knowing your exact situation it's difficult to say specifically.
WAR and JAR files are basically .zip files, so if you have the location of the file containing the .properties file you want you can just open it up using ZipFile and extract the properties.
If it's a JAR file though, there may be an easier way: you could just add it to your classpath and load the properties using something like:
SomeClass.class.getClassLoader().getResourceAsStream("maven.properties");
(assuming the properties file is in the root package)

Related

Reading file inside Spring boot fat jar

We have a spring boot application which has a legacy jar api that we use that needs to load properties by using InputFileStream. We wrapped the legacy jar in our spring boot fat jar and the properties files are under BOOT-INF/classes folder. I could see spring loading all the relevant properties but when I pass the properties file name to the legacy jar it could not read the properties file as its inside the jar and is not under physical path. In this scenario how do we pass the properties file to the legacy jar?
Please note we cannot change the legacy jar.
Actually you can, using FileSystem. You just have to emulate a filesystem on the folder you need to get the file from. For example if you wanted to get file.properties, which is under src/main/resources you could do something like this:
FileSystem fs = FileSystems.newFileSystem(this.getClass().getResource("").toURI(), Collections.emptyMap());
String pathToMyFile = fs.getPath("file.properties").toString();
yourLegacyClassThatNeedsAndAbsoluteFilePath.execute(pathToMyFile)
I also have faced this issue recently. I have a file I put in the resource file, let's call it path and I was not able to read it. #madoke has given one of the solutions using FileSystem. This is another one, here we are assuming we are in a container, and if not, we use the Java 8 features.
#Component
#Log4j2
public class DataInitializer implements
ApplicationListener<ApplicationReadyEvent> {
private YourRepo yourRepo; // this is your DataSource Repo
#Value(“${path.to.file}”). // the path to file MUST start with a forward slash: /iaka/myfile.csv
private String path;
public DataInitializer(YourRepo yourRepo) {
this.yourRepo = yourRepo;
}
#Override
public void onApplicationEvent(ApplicationReadyEvent event) {
try {
persistInputData();
log.info("Completed loading data");
} catch (IOException e) {
log.error("Error in reading / parsing CSV", e);
}
}
private void persistInputData() throws IOException {
log.info("The path to Customers: "+ path);
Stream<String> lines;
InputStream inputStream = DataInitializer.class.getClassLoader().getResourceAsStream(path);
if (inputStream != null) { // this means you are inside a fat-jar / container
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
lines = bufferedReader.lines();
} else {
URL resource = this.getClass().getResource(path);
String path = resource.getPath();
lines = Files.lines(Paths.get(path));
}
List<SnapCsvInput> inputs = lines.map(s -> s.split(","))
.skip(1) //the column names
.map(SnapCsvInput::new)
.collect(Collectors.toList());
inputs.forEach(i->log.info(i.toString()));
yourRepo.saveAll(inputs);
}
}
Basically, you can't, because the properties "file" is not a file, it's a resource in a jar file, which is compressed (it's actually a .zip file).
AFAIK, the only way to make this work is to extract the file from the jar, and put it on your server in a well-known location. Then at runtime open that file with an FileInputStream and pass it to the legacy method.
According to #moldovean's solution, you just need to call 'getResourceAsStream(path)' and continue with returned InputStream. Be aware that the 'path' is based on ClassPath. For example:
InputStream stream = this.getClass().getResourceAsStream("/your-file.csv");
In root of your class path, there is a file named 'your-file.csv' that you want to read.

Log4j doesn't see .properties file

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:

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.

Properties keep driving me crazy. Can't save it! "FileNotFound"

these properties keep driving me crazy. I'm reading everywhere, that even loading the properties should be no problem by just using:
Properties p = new Properties();
p.load(new FileInputStream("filename.properties");
Though in my case it doest work. Java is not finding the file, which is located in the class directory! Thats why i HAD TO use it with the Assetmanager:
String defaultProfileProperties = "filename.properties";
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
final Properties properties = new Properties();
try {
InputStream inputStream = assetManager.open(defaultProfileProperties);
properties.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open " + defaultProfileProperties + " property file");
e.printStackTrace();
}
Putting the filename.properties in the assets-folder.
Well, now I simply can't save the properties-file by using .store(out,comment) ...
I tried using a FileOutputStream with the path set to either "filename.properties", or "assets/filename.properties". Neither of them worked. I even added a slash here and there, but nothing is helping! I'm not finding any tutorials on the web, nor ppl having the same problem!
Could you please just help me? I guess this is such a simple thing, but i'm not getting a clue how to ... blah
If you open a file with FileInputStream, then the starting directory (relative path) is based on the working directory when you started java, NOT the classpath. Opening a file with resources will reference the classpath entries.
Have you tried using a full path when using FileInputStream()? Try that and see if it works, and if it does, then you'll need to either set the working directory at start up and/or reference your file via relative path from the start directory.
Try this:
InputStream in = this.getClass().getResourceAsStream("filename.properties");
Properties p = new Properties();
p.load(in);

Categories