Unable to load external files in java while running in terminal - java

I have created a executable jar package (called myjar.jar) which has a class for reading config file(called config_reader) .There is another class file outside myjar.jar which uses the config_reader. But the config file for config_reader is placed outside the myjar.jar ( in local filesystem) .Now when i try to execute the executable jar along with another file that uses it i get an error saying config file not found :
I tried to :
java -classpath config myclass.class
can Anyone help out on this ?
The code of config_reader is :
public class config_reader()
{
public static ArrayList<String> get_prop()
{
Properties prop = new Properties();
ArrayList<String> s= new ArrayList<String>();
try {
//load a properties file
prop.load(new FileInputStream("config"));
//get the property value and print it out
s.add(prop.getProperty("source_folder_dir"));
s.add(prop.getProperty("dest_folder_dir"));
s.add(prop.getProperty("file_type"));
s.add(prop.getProperty("username"));
s.add(prop.getProperty("userpwd"));
s.add(prop.getProperty("exclusion_list"));
} catch (IOException ex) {
ex.printStackTrace();
}
return s;
}
}

prop.load(new FileInputStream("config"));
Instead of just saying config use absolute path to the file. Infact it is better to do
File configFile = new File("absolute path to config file");
if(configFile.exists()){
//continue with your logic
}

Related

How to load external properties file with Java without rebuilding the Jar?

I use gradle which structures projects in maven style so I have the following
src/main/java/Hello.java and src/main/resources/test.properties
My Hello.java look like this
public class Hello {
public static void main(String[] args) {
Properties configProperties = new Properties();
ClassLoader classLoader = Hello.class.getClassLoader();
try {
configProperties.load(classLoader.getResourceAsStream("test.properties"));
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?
You can try this one, which will first try to load properties file from project home directory so that you don't have to rebuild jar, if not found then will load from classpath
public class Hello {
public static void main(String[] args) {
String configPath = "test.properties";
if (args.length > 0) {
configPath = args[0];
} else if (System.getenv("CONFIG_TEST") != null) {
configPath = System.getenv("CONFIG_TEST");
}
File file = new File(configPath);
try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
Properties configProperties = new Properties();
configProperties.load(input);
System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can send the properties file path as argument or set the path to an environment variable name CONFIG_TEST
Archaius may be complete overkill for such a simple problem, but it is a great way to manage external properties. It is a library for handling configuration: hierarchies of configuration, configuration from property files, configuration from databases, configuration from user defined sources. It may seem complicated, but you will never have to worry about hand-rolling a half-broken solution to configuration again. The Getting Started page has a section on using a local file as the configuration source.

Open a properties file from a class in a Dynamic Web Project

I'm using Eclipse for EE Developer.
I need to access to a properties file (db.properties) from a class's method (DBQuery.java).
The class is located inside a package inside the src folder.
For the properties file i tried almost everything that i could find over the net to make it work, but looks like i can't.
The properties file is located inside the WebContent folder, and i'll add the code with which i'm trying to load this file:
public class DBQuery {
public static String create_DB_string(){
//the db connection string
String connString = "";
try{
Properties props = new Properties();
FileInputStream fis = new FileInputStream("db.properties");
props.load(fis);
fis.close();
/* creating connString using props.getProperty("String"); */
}
catch (Exception e) {
System.out.println(e.getClass());
}
return connString;
}
}
So my question is, where to put the properties file, and which is the correct way to load it?
You can put this propertie file within your java package for example com/test and use following:
getClass().getResourceAsStream( "com/test/myfile.propertie");
Hope it helps.

Reading Properties file inside conf folder

I have a properties file which is located under conf folder. conf folder is under the project root directory. I am using the following code.
public class PropertiesTest {
public static void main(String[] args) {
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("/conf/sampleprop.conf");
Properties prop = new Properties();
try {
prop.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(prop.getProperty("TEST"));
}
}
But I get nullpointer exception.
I have tried using
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("./conf/sampleprop.conf");
and
InputStream inputStream = PropertiesTest.class
.getResourceAsStream("conf/sampleprop.conf");
But all result in nullpointer exception.
Can anyone please help.
Thanks in advance
Try to recover your working directory first:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working dir: " + workingDir);
and then is simple:
Properties propertiesFile = new Properties();
propertiesFile.load(new FileInputStream(workingDir+ "/yourFilePath"));
String first= propertiesFile.getProperty("myprop.first");
Regards, fabio
The getResourceAsStream() method tries to locate and load the resource using the ClassLoader of the class it is called on. Ideally it can locate the files only the class folders .. Rather you could use FileInputStream with relative path.
EDIT
if the conf folder is under src, then you still be able to access with getResourceAsStream()
InputStream inputStream = Test.class
.getResourceAsStream("../conf/sampleprop.conf");
the path would be relative to the class from you invoke getRes.. method.
If not
try {
FileInputStream fis = new FileInputStream("conf/sampleprop.conf");
Properties prop = new Properties();
prop.load(fis);
System.out.println(prop.getProperty("TEST"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
NOTE: this will only work if it is Stand alone application/in eclipse. This will not work if its web based (as the root will be Tomcat/bin, for eg)
I would suggest to copy the configuration file at designated place, then you can acess at ease. At certain extent 'System.getProperty("user.dir")' can be used if you are always copying the file 'tomcat` root or application root. But if the files to be used by external party, ideal to copy in a configurable folder (C:\appconf)
Your code works like a charm! But you might have to add the project root dir to your classpath.
If you work with Maven, place your configuration in src/main/resources/conf/sampleprop.conf
When invoking java directly add the project root dir with the java -classpath parameter. Something like:
java -classpath /my/classes/dir:/my/project/root/dir my.Main

Cannot load properties from jar

I have small app and I tested and packed to jar and am trying to run it but I have error.
Here is my project structure:
src
-kie.template
----- ServerMain.java ==> Class with main
-kie.template.util
---- PropUtils.java
---- server.properties
target
-kietemplate.jar
---- lib
In the main method, PropUtils class reads properties.
public class PropUtils {
private static final String PROPERTIES = "server.properties";
public static Properties load() {
Properties properties = new Properties();
InputStream is = null;
try {
properties.load(PropUtils.class.getResourceAsStream(PROPERTIES));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is!=null) try{is.close();}catch(IOException e){}
}
return properties;
}
}
}
When I run the ServerMain class directly, it works fine. But after I packed it to jar and run, it shows error:
java -cp lib -jar kietemplate.jar
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at au.org.jeenee.kie.template.util.PropUtils.load(PropUtils.java:26)
The properties file is in the directory when I look into the jar file.
jar tf kietemplate.jar
Any help would be appreciated very much.
EDIT:
I changed the logic to read properties:
Properties properties = new Properties();
InputStream is = null;
try {
File file = new File("server.properties");
is = new FileInputStream(file);
properties.load(new InputStreamReader(is));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is!=null) try{is.close();}catch(IOException e){}
}
It requires the properties file in parent directory of the jar file.
Your code works fine on my computer, both from the JAR and the filesystem.
A possible cause for that behaviour is the filesystem being case insensitive, but the jar file being case sensitive. But we really can't tell from the source code alone.

reading config file from different folder java

I am trying to read a config file based on the code here:
http://www.opencodez.com/java/read-config-file-in-java.htm
So I found that if the config.cfg is in same directory as of where I am running the code, then everything is fine but if the config is at different directory
example: /path/to/config.cfg
I get this error:
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at packagename.conf.Config.<init>(Config.java:14)
at packagename.conf.Config.main(Config.java:30)
My guess is it is not able to find the file.
But how do I modify the above code to read config file from a different folder?
Thanks
Edit: Code from the link:
import java.util.*;
import java.util.Properties;
public class Config
{
Properties configFile;
public Config()
{
configFile = new java.util.Properties();
try {
configFile.load(this.getClass().getClassLoader().
getResourceAsStream("myapp/config.cfg"));
}catch(Exception eta){
eta.printStackTrace();
}
}
public String getProperty(String key)
{
String value = this.configFile.getProperty(key);
return value;
}
}
The code that you posted expects the configuration-file to be on the classpath (that is, in the same sorts of places that Java looks for your .class files). So, you can either include the directory containing the configuration-file in the classpath:
java -classpath .:/path/to packagename.conf.Config
Or else you can modify the code to expect the configuration-file to be a regular filesystem file:
final InputStream cfg = new FileInputStream("/path/to/config.cfg");
try
{ configFile.load(cfg); }
finally
{ cfg.close(); }

Categories