WebSphere/Liberty :- Reading data file

Background

Having to read a data file and wanted to see the options available.

Let us go over some of those options.

Option

  1. API :- File / File Reader
    • Location
      • File System
        • Sample
          • /home/
          • /WEB-INF/datafile/dbo.users.txt
  2. API :- classLoader.getResourceAsStream
    • Location
      • File System
        • relative to class path
        • Sample
          • \datafile\dbo.users.txt

Packaging

Using https://extract.me/, an online WAR file extractor we can visualize our targeted layout.

Image

rearfileDOTwar_20180724__20180724__0827PM

Explanation

  1. WEB-INF
    • Artifacts
      • Read Method
        • API :- File
      • Sample
        • datafile
          • dbo.users.txt
    • Java Classes
      • Read Method
        • API :- Class Loader
      • Sample
        • datafile
          • dbo.users.txt

Configuration

The location of our file can be saved in various locations.

web.xml

In our case we will save in the web.xml file.

Image

webDOTxml_20180724_0402PM.png

Source

Read web.xml and get servlet parameters


 private void getDataFilePath
(
    PrintWriter out
)
{

    ServletConfig config;

    config = getServletConfig();

    String initparamValue;      

    Enumeration enumeration = null;

    String parm;

    enumeration = getInitParameterNames();

    while (enumeration.hasMoreElements())
    {
        parm = enumeration.nextElement();

        strLog = parm
                    + " "
                    + getInitParameter(parm)
                    + ""
                    ;

        out.println(strLog);

    }

    //datafileOS
    initparamValue = config.getInitParameter
                        ("datafileOS");

    strDatafileOS = initparamValue;

    //datafileResource
    initparamValue = config.getInitParameter
                        ("datafileResource");

    strDatafileResource
        = config.getServletContext().getRealPath(initparamValue);

    //datafileOS
    initparamValue = config.getInitParameter
                        ("datafileClass");

    strDatafileClass = initparamValue;

}   

Reading Text File through File API


private BufferedReader getBufferedReaderUsingTraditionalMethod
(
      String strDatafile
    , PrintWriter out
)
{

    BufferedReader bufferedReaderLocal = null;

    try
    {   

        file = new File(strDatafile);

        if (file != null)
        {

            fileReader = new FileReader(file);

            bufferedReaderLocal = new BufferedReader(fileReader);

        }
    }
    catch (Exception ex)
    {

        ex.printStackTrace();

        System.out.println(ex.getMessage());

    }

    return(bufferedReaderLocal);

}

Reading as Class File


private BufferedReader getBufferedReaderUsingClassLoader
(
	  String strDatafile
	, PrintWriter out
)
{

	BufferedReader bufferedReaderLocal = null;

	try
	{

		classLoader = getClass().getClassLoader();

		objInputStream = classLoader.getResourceAsStream(strDatafile);

		if (objInputStream == null)
		{

			return (bufferedReaderLocal);

		}
		else
		{	

			bufferedReaderLocal = new BufferedReader
				(
					new InputStreamReader(objInputStream)
				);

		}

	}
	catch (Exception ex)
	{

		ex.printStackTrace();

		System.out.println(ex.getMessage());

		out.println(ex.getMessage());

	}

	return (bufferedReaderLocal);

} 	

Read data file


private void readDatafile(PrintWriter out )
{

    BufferedReader bufferedReader = null;

    StringBuffer stringBuffer = null;
    String line;
    long lNumberofRecordsRead = 0;

    Collection objListDisplayName = new ArrayList();    

    try
    {

        strDatafile = strDatafileOS;

        // Read OS File
        bufferedReader = getBufferedReaderUsingTraditionalMethod
                         (
                              strDatafile
                            , out
                         );

        // If unable to read OS File
        // read data file from web.inf/
        if (bufferedReader == null)
        {

            strDatafile = strDatafileResource;

            bufferedReader = getBufferedReaderUsingTraditionalMethod
                                (
                                      strDatafile
                                    , out
                                );

        }

        //servlet class file
        if (bufferedReader == null)
        {

            strDatafile = strDatafileClass;

            bufferedReader = getBufferedReaderUsingClassLoader
                                (
                                      strDatafile
                                    , out
                                );

        }           

        if (bufferedReader == null)
        {
            return;
        }

        stringBuffer = new StringBuffer();

        while ((line = bufferedReader.readLine()) != null)
        {

            objListDisplayName.add(line);

            lNumberofRecordsRead = lNumberofRecordsRead + 1;

        }

        if (fileReader != null)
        {
            fileReader.close();
        }

        if ( classLoader != null)
        {
            classLoader = null;
        }

        if (objInputStream != null)
        {
            objInputStream = null;
        }

        if (bDebug)
        {
            strData = lNumberofRecordsRead
                        + " record(s) read";

            out.println(strData);

        }

    }
    catch (IOException ex)
    {

        ex.printStackTrace();

        System.out.println(ex.getMessage());

        out.println(ex.getMessage());

    }

}

DisplayReadFile

private void displayReadFile(PrintWriter out )
{

    long i = 0;

    iterator = objListDisplayName.iterator();

    String strData;

    strData = "";

    out.println(strData);

    // while loop
    while (iterator.hasNext())
    {

        i = i + 1;

        strData = "
                    + iterator.next()
                    + ""
                    ;

        out.println(strData);

        if (i == 6)
        {
            break;
        }

    }

}

Source Code

DanielAdeniji/javaReadFileText
Link

Dedicated

Dedicated to Ivan S. & Joe L.

I was really struggling with this.

But, these brothers wrestled with me and made sure I did not get it wrong.

And, so here is gratitude for brothers who take time and think we deserve better; especially when we clearly don’t.

Ivan S.

ivanS_20180724_0456PM

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s