JAVA - Read configuration file from Eclipse and JAR - java

I need to properly set the path (or the tree structure in Eclipse) to read a configuration file both in a development environment (Eclipse) and production environment (by running a jar file).
Currently, I read the file in two ways:
- public String getProperty(String parameter) {
String property = null;
try {
//prop.load(getClass().getClassLoader().getResourceAsStream("configuration.properties"));
prop.load(getClass().getClassLoader().getResourceAsStream("src/configuration.properties"));
property = prop.getProperty(parameter);
}
catch (IOException e) {
e.getMessage();
}
return property;
}
- try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
...
}
The problem is with the first method: in Eclipse I have to set
getResourceAsStream("configuration.properties"));
while for jar I have to add src
getResourceAsStream("src/configuration.properties"));
since the jar file is located at the same level of a src folder containing the configuration file.
For the FileReader method the src/configuration.properties path works fine in both cases.
In Eclipse I have the following tree structure:
ProjectName
+ src/
+ filePackage/
FileLoader.java
+ config_file
How could I manage both cases using a common approach/path?
Thanks

Related

Java - Get file from jar

I need to catch some directory within the application. For that I have a small demonstration:
String pkgName = TestClass.class.getPackage().getName();
String relPath = pkgName.replace(".", "/");
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
File file = new File(resource.getPath());
System.out.println("Dir exists:" + file.exists());
While running application from IDE I receive my goal and I can find my directory. But running application as JAR file, does not return a valid "file" (from Javas perspective) and my sout gives me back File exists:false. Is there some way to get this file? In this case, the file is a directory.
Java ClassPath is an abstraction that differs from a filesystem abstraction.
A classpath element may exist in two physical ways:
exploded with classpath pointing to the root directory
packed in a JAR archive
Unfortunatelly, the file.getPath does return a File object if classpath is pointing to file system but it does not if you refer to a JAR file.
In 99% of all cases you should read the contents of a resource using InputStream.
Here is a snippet, that uses IOUtils from apache commons-io to load the whole file content into a String.
public static String readResource(final String classpathResource) {
try {
final InputStream is = TestClass.class.getResourceAsStream(classpathResource);
// TODO verify is != null
final String content = IOUtils.toString(
is, StandardCharsets.UTF_8);
return content;
} catch (final IOException e) {
throw new UncheckedIOException(e);
}
}

java.io.FileNotFoundException: config.properties

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.

About citing external files in java application

I am writing a java application, in which I am automatically importing external csv files in background to do the computation. But the problem is that I am using "absolute" file path in my java program, the generated jar file will not work in another computer. Is there anyway in java to use a kind of "working directory path" so that I can still run the jar file in another computer as long as I put the csv files I'd like to import in the same folder with the jar file?
Thanks!
You can read a file using its name like
try (BufferedReader br = new BufferedReader(new FileReader("text.txt"))) {
String line;
while ((line=br.readLine())!=null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
Here text.txt should be in the same working directory where the jar was executed.
You can also read the directory name from the command line, using the command line arguments like
public static void main(String[] args) {
//check if there were any command line arguments
if (args.length > 0) {
// args[0] is the first command line argument unlike C where args[0] would give u the executable's name
} else {
System.err.println("Usage: java -jar <jar_name> [directory_names..]");
}
}
You can also have a configuration file such as a properties file to read the directory names.
new File(".") give you the relative path
you can write relative path like that :
File file = new File(".\\CSVs\\myfile.csv");
System.getProperty("user.dir") will return you the working directory.
System.getProperty("user.dir")+"\\myfile.txt"
More informations here :system properties, oracle docs

Property file not being read from jar

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.

Full path decleration for a file path used in java for jsp web app

I want to be able to have my paths work on any server not just my dev box.
Right now I declear the full path of the file name as such on my local drive.
filename = "H:\test\SourceCode\sample\src\file.txt"
try
{
BufferedReader in = new BufferedReader(new FileReader(fileName));
line = in.readLine();
in.close();
}
catch (IOException e) {
log.error("Exception Message", e);
}
How can I set the file path so when I create the .war file I can use it on any server. Such as filename = "src/file.txt" (This doesn't work for me)
Two usual ways:
getClass().getResourceAsStream("/..") - resolves the path relative to the classpath - that is, WEB-INF/classes (and jar files)
getServletContext().getResourceAsStream("/..") resolves the path relative to the webapp root. That is - webapps/applicationname

Categories

Resources