Following code works fine on windows:
private static Properties getProps() throws FileNotFoundException, IOException {
Properties properties = new Properties();
File externalFile = new File("myProp.properties");
if(externalFile.exists()) //if an external property file exists within the same path it is prioritized
properties.load(new FileInputStream(externalFile));
else{
properties.load(CommandUtil.class.getClass().getResourceAsStream("/com/localpath/default.properties"));
}
return properties;
}
if myProp.properties exists within the same folder of the .jar, then this property file is read, otherwise default .properties file contained inside of the .jar itself will be taken.
When I move this program on a linux system it does not work anymore: even though there is a .properties file beside the .jar this is just ignored.
Why is that?
Related
I have a simple program in Intellij that I made just to test out reading file path of config file.
I created a simple test case where I would use a timer to print "Hello world" periodically in N intervals where N is in milliseconds and N is configurable.
This is the code:
public void schedule() throws Exception {
Properties props=new Properties();
String path ="./config.properties";
FileInputStream fis=new FileInputStream(path);
BufferedReader in1=new BufferedReader(new InputStreamReader(fis));
// InputStream in = getClass().getResourceAsStream("/config.properties");
props.load(in1);
in1.close();
int value=Integer.parseInt(props.getProperty("value"));
Timer t=new Timer();
t.scheduleAtFixedRate(
new TimerTask() {
#Override
public void run() {
// System.out.println("HELEOELE");
try {
// test.index();
System.out.println("hello ");
} catch (Exception e) {
e.printStackTrace();
}
}
},
0,
value);
}
What I did was I set value as N in a config file where it can be changed by anyone without touching the actual code. So I compiled the jar file, and I placed both config.properties and jar file in same folder or directory. I want to be able to change make N changeable so I don't need to re-compile the jar again and again everytime.
Note: the config properties file is created manually and placed in same directory as the jar. And I am executing the jar in command prompt.
However, it seems when I try to run it, it doesn't recognize the file path.
"main" java.io.FileNotFoundException: .\config.properties (The system cannot find the file specified)
I've looked into many issues regarding reading config files outside of jar file and none of them worked for me. Am I doing any mistake here?
./config.properties is a relative path that points to a config.properties file in the current working directory.
The current working directory, unless changed by System.setProperty("user.dir", newPath), will be the directory from which you launched the JVM currently handling your code.
To get your jar to work as it currently is, you have two ways available :
copy the config.properties file to the directory you are executing java from
change the directory you are running java from to the one that contains the config.properties
You may also consider letting the user specify where to get the properties file from :
String path = System.getProperty("propertiesLocation", "config.properties");
You would then be able to specify a location for the property file when calling your jar :
java -jar /path/to/your.jar -DpropertiesLocation=/path/to/your.properties
Or call it as you did before to search for the properties at its default location of config.properties in the current working directory.
I want to use a small program as a dependency in my Maven project. This program is configured by a properties file which can be edited before its execution. So far I have added the dependency as JAR in a local repository.
Now I want to make that dependency's properties file accessible in my own superior classpath, i.e. in myprogram/src/main/resources/config/myprogram.properties and not in myprogram/local-repository/com/example/mydependency/mydependency.jar/mydependency.properties.
I tried to modify the part of the code where the path for the properties file is defined:
public example() {
Properties prop = new Properties();
InputStream input = example.class.getResourceAsStream("/config/myprogram.properties");
prop.load(input);
...
}
I also deleted the original properties file of the dependency before adding it to my local repository.
The whole program is working, but not as expected. Strangely, neither my new properties file in /src/main/resources/config nor the old one in the mydependency.jar is used. It seems that some kind of default properties file is put into my final fat JAR. But I cannot find its source anywhere - even when I try to debug it. That default properties file just seems to appear out of nowhere.
Now, how can I properly move the dependency's properties file to my own classpath?
And where could this default properties file appear from?
Is this an issue with Maven or with the source code itself?
Thanks in advance!
You can do something like this:
public static String getValueFromDependencyProps(ClassLoader cl, String propertiesFile, String key) throws IOException {
Properties prop = new Properties();
prop.load(cl.getResourceAsStream(propertiesFile));
String value = prop.getProperty(key);
if (value == null)
throw new NullPointerException();
else
return value;
}
And then:
String value = getValueFromDependencyProps(YourDependencyClass.class.getClassLoader(), "your.properties", key);
Tested and working. With that I'm able to access any properties file from an external Maven dependency (using one of its classes, YourDependencyClass, to reach it).
I have a certain requirement where I need to copy files from Unix server to Windows Shared Drive. I am developing the necessary code for this in Java. I am a beginner so please excuse me for this basic question.
I have my source path in my config file. So, I am using the below code to import my config file and set my variable. My Project has config.properties file attached to it.
public static String rootFolder = "";
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Config files not able to set properly for Dest Folder");
}
try {
prop.load(input);
rootFolder = prop.getProperty("Dest_Root_Path");
System.out.println("Destination Folder is being initialized to - "+rootFolder);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Destination Path not set properly");
}
When I am doing this I am getting an error saying the file is not found.
java.io.FileNotFoundException: config.properties (No such file or directory)
at java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.io.FileInputStream.<init>(FileInputStream.java:113)
Exception in thread "main" java.lang.NullPointerException
at java.util.Properties.load(Properties.java:357)
I am triggering this jar using a unix ksh shell. Please provide guidance to me.
Put your config file somewhere within the classpath. For example, if it's a webapp, in WEB-INF/classes. If it isn't a webapp, create a folder outside the project, put the file there, and set the classpath so the new folder is in it.
Once you have your file in the classpath, get it as a resource with getResourceAsStream():
InputStream is = MyProject.class.getResourceAsStream("/config.properties");
Don't forget the slash / before the filename.
I have made a Java (.jar) application that uses and external image and MS Access database.
Both things are accessed using a path. This won't work if I give the application to my friend to test as the path wont match.
I was wondering if I could make configuration settings file that would change the path by editing the settings file and make the application work fine instead of opening the source code in editor and editing there.
Yes you can do it by creating a configuration file. Lets say your configuration file is "config.properties". You can mention properties required in file like
#comment
imageFile=C://imagePath
database=<path to db>
username=
password=
Then read the file
Properties properties = new Properties();
InputStream in = null;
in= new FileInputStream("config.properties");
//load a properties file
properties.load(input);
// get the property value and print it out
System.out.println(properties.getProperty("imageFile"));
---
Make sure file is accessible by keeping it in classpath.
Properties properties;
try(InputStream input = this.getClass().getClassLoader().getResourceAsStream("app.properties")) {
properties = new Properties();
properties.load(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
System.out.println(properties.getProperty("my.path"));
Property file format is very simple
my.path = /home/file.txt
semicolon_Also_delimiter:value
semicolon\:can\:be\:escaped:value
I have a simple maven project that reads properties from src/main/resources, and runs perfectly fine in eclipse, but when I export this application as a runnable jar although it tells me Exporting resources/test.properties while building the jar, it breaks unless I include the test.properties file in the location I am invoking my shell script from. Why does this happen? How does it work fine in eclipse? When I look into the jar file contents, it is exactly in the same folder - resources, but command line is just not working. Any advise?
Here is the code that reads the properties from the file -
public class Test {
private static Properties properties = new Properties();
static{
InputStream is = null;
try{
is = Test.class.getClassLoader().getResourceAsStream("test.properties");
if(is!=null)
properties.load(is);
}catch(Exception e){
throw new TestException("Unable to load the properties file :" + e.getMessage(), e);
}finally {
IOUtils.closeQuietly(is);
}
}
public static String getProperty(String key){
return properties.getProperty(key);
}
public static String getProperty(String key, String defaultValue){
return properties.getProperty(key, defaultValue);
}
To get any property, I invoke the getProperty method.
Oh, right. I think Eclipse builds the .jar incorrectly. In maven all files in src/main/resources/* are packaged into /*, but you are saying that your jar has the file as /resources/test.properties, and the getResourceAsStream("test.properties") expects the file in the root folder, not inside /resources. This is wrong. Use maven to build .jar.