Simple Java Utils Library source code.

Today I’m including a couple of general purpose Java Source code files.

/*
------------------------------------------------------------------------
 $Id: Util.java,v 1.1 2012/03/14 16:16:49 ddemartini Exp $
 $Revision: 1.1 $
 $Date: 2012/03/14 16:16:49 $
 $Name:  $
------------------------------------------------------------------------
 Utilities

 Added file utilities
------------------------------------------------------------------------
*/

package base;
import java.io.UnsupportedEncodingException;
import java.io.File;
import java.util.*;

public class Util {
      
  /* retrieve environment or -D options passed by implementer */
  public static String envOrProp(String name) {
    if (System.getenv(name) != null) {
      return System.getenv(name);
    }
    else if (System.getProperty(name) != null) {
      return System.getProperty(name);
    }
    else {
      return null;
    }
  } /* envOrProp */

  /* Open a file stream and test for read */
  private static File fhRead(String inFile) throws Exception {
    File rf = openFile(inFile);
    try {
      // verify file exists and is readable
      if(! rf.exists() || !rf.canWrite()){
        System.out.println("Unable to read file "+inFile);
        return null;
      }
    } catch (Exception e) {
       System.out.println("Fatal error attempted to open stream from "+inFile+"\n"+e);
       return null;
    }
    return rf;
  } /* fhRead */

  /* Open a file steam for writing */
  private static File fhWrite(String outFile) throws Exception {
    File of = openFile(outFile);
    try {
      // verify file would be writable 
      if(!of.canWrite()){
        System.out.println("Unable to read file "+outFile);
        return null;
      }
    } catch (Exception e) {
       System.out.println("Fatal error attempted to open stream to "+outFile+"\n"+e);
       return null;
    }
    return of;
  } /* fhWrite */

  /* Attempt to open a file handle */
  private static File openFile(String inFile) throws Exception {
    File file;
    try {
      file = new File(inFile);  // open file handle
    } catch (Exception e) {
       System.out.println("Fatal error attempted to open stream to "+inFile+"\n"+e);
       return null;
    }
    return file;
  } /* openFile */

} /* Util */

Subsequent source code using this utility file will be documented later.