Reading a Properties File for a Java Application using NetBeans IDE
This article introduces you to a step-by-step process for developing Java (or JFC) based applications with Microsoft SQL Server as the database, using NetBeans IDE. It is the second in a series, and focuses on showing you how to read the properties file.
Reading a Properties File for a Java Application using NetBeans IDE - How to get the current working folder (or where the current class file exists) in Java (Page 2 of 5 )
The previous section dealt with retrieving the current class file name (along with the class name). I would like to utilize it here to get the class file name first, and then extend it to get the current working folder.
Let us go through the following code first:
public String getLocalDirName() { String localDirName;
//Use that name to get a URL to the directory we are executing in java.net.URL myURL = this.getClass().getResource (getClassName()); //Open a URL to the our .class file
//Clean up the URL and make a String with absolute path name localDirName = myURL.getPath(); //Strip path to URL object out localDirName = myURL.getPath().replaceAll("%20", " "); //change %20 chars to spaces
//Get the current execution directory localDirName = localDirName.substring (0,localDirName.lastIndexOf("/")); //clean off the file name
return localDirName; }
I shall explain the above program part by part. Let us first consider the following:
You can observe that I am using the method "getClassName()" in the previous section. When the statement gets executed, it gives us the entire execution path of the current class in the form of an URL (including the class name and other URL stuff). Now, we need to extract the exact path (only the folder information) and return the same to the calling program. Further proceeding,we have the following:
//Clean up the URL and make a String with absolute path name localDirName = myURL.getPath(); //Strip path to URL object out localDirName = myURL.getPath().replaceAll("%20", " "); //change %20 chars to spaces
The above statements simply clean out the URL stuff. Every URL shall have some characters encoded (such as spaces). In the above statement, I only took care of the spaces. If your path includes any other encoded characters, you need to replace them accordingly. Further proceeding, we have the following:
//Get the current execution directory localDirName = localDirName.substring (0,localDirName.lastIndexOf("/")); //clean off the file name
The above would simply trim off anything which is after the last folder slash (in this case it is the file name), resulting in only the folder name and its path! We finally return the same to the calling function by issuing the following statement.
return localDirName;
The upcoming sections will provide you with few step-by-step guidelines for dealing with the ".properties" file in Java.