Reading the Resource or Property files in Java as a file stream and outputting the content to console

A good programming practice is to avoid hardcoding values in your Java File. These values should be read from some resource files or proerty files. The major benefit of doing that is that in case you decide to alter those values, there is no need to recompile your classes. Another benefit is the isolation of the resources from the logic.

Is it difficult to read the resource from a file on to the Java class? No, it’s pretty simple. The following sample code that I wrote shows how easily you can read the content of your file as a stream. How you use the value thus read in your Java file is up to you. I have only demonstrated how the resource is actually read.

This program does the following:

  • Read resource file as a stream from Java class
  • Print the content of the resource file onto the Java console.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * Created on 2012-07-03
 * Last Modified on 2012-07-03
 *
 * This class demonstrate how we can read the resource files as file input stream.
 * - Reads a resource file
 * - Prints file contests on to the console.
 */

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadResourceFile {

	public static void main(String args []) throws Exception {
		readResourceFileAndPrintContents();
	}

	private static void readResourceFileAndPrintContents() throws Exception {
		/** Get the input stream for the resource file**/
		InputStream stream = loadResourceAsStream ("C:/temp/myresources.properties");

		/**Create a BufferedReader object for the input stream**/
		BufferedReader in = new BufferedReader(new InputStreamReader(stream));

		/**Read the lines and print them onto the console**/
		String line;
	    while ((line = in.readLine()) != null) {
	        System.out.println((line));
	    }
	}

	/**
	 * This method
	 * - Takes a resource file name as parameter
	 * - Returns the InputStream object of FileInputStream type
	 */
	public static InputStream loadResourceAsStream(final String resourceName) {
		InputStream input = null;
		try {
			input = new FileInputStream(resourceName);
		} catch (FileNotFoundException e) {
			System.out.println("Resource File Not Found");
			e.printStackTrace();
		}
		return input;
	}

}

Content of the file c:/temp/myresources.properties

server=www.thisismyfantasticvirtualserver.com
port=1005
userid=mickeyrourke
password=dontcopymypasswordplease

Here is the output of this program, which is same as the content of the file. The java class simply read the resource file as stream and spit out the content onto the console.

server=www.thisismyfantasticvirtualserver.com
port=1005
userid=mickeyrourke
password=dontcopymypasswordplease

Reading / Writing File in Java and String Manipulation

I wrote this piece of java code because I encountered a situation where I had a list of some strings from some table in database and needed to create an in clause. Since the number of items was huge, it was not possible to manually add quote the string and add a comma.

Here was my requirement.

I had string in the following format:

14685
14701
14707
14720
14738
14741
14743
14745
14747
14748
14749
14750
14751
14761
14764
14767
14768
14771
14775
14776

And I needed the string formatted something like the following so that I could put that in ‘in clause’ in one of the SQL.

‘14685’,  ‘14701’,  ‘14707’,  ‘14720’,  ‘14738’,  ‘14741’,  ‘14743’,  ‘14745’,  ‘14747’,  ‘14748’,
‘14749’,  ‘14750’,  ‘14751’,  ‘14761’,  ‘14764’,  ‘14767’,  ‘14768’,  ‘14771’,  ‘14775’,  ‘14776’

So, to save my time doing the impossible manual change (I had around 2000 of these items), I wrote this simple program. This program features File Read, File Write operation in Java and also shows simple Java String manipulation techniques.

package com.kushal.sql.utilities;
/**
 * @author Kushal Paudyal
 * Created on 10/02/2008
 * www.sanjaal.com/java
 *
 * Demonstrates the following Java features
 * --Reading a File in Java
 * --Simple String manipulations
 * --Writing to a File in Java
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class FormInStringForSQL {

	public static void main(String args [])
	{
		try{
			String inputFileName="C:/items_that_were_marked.txt";
			String outputFileName="C:/myoutputfile.txt";

			BufferedReader in = new BufferedReader(new FileReader(inputFileName));
			String line="";
			int count=0;
			String formattedStringForInClause="";

			/**Read the file and do the necessary formatting**/
			while ((line = in.readLine()) != null)
			{
				if(count%10>0) /**Formatting to 10 columns**/
					formattedStringForInClause+=" '"+line+"', ";
				else
					formattedStringForInClause+="n '"+line+"', ";
				count++;
			}

			/**Removing the trailing final comma (')**/
			if(formattedStringForInClause.endsWith(", "))
				formattedStringForInClause=
                                formattedStringForInClause.substring(
				0,formattedStringForInClause.length()-2);

			/**Writing the formatted string to file**/
			BufferedWriter out = new BufferedWriter(new FileWriter(outputFileName));
	        out.write(formattedStringForInClause);
	        out.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}