Tuesday, September 27, 2016

Java - How to Write to a File.

public class FileTrace implements Trace {
          
      private java.io.PrintWriter pw;
      private boolean debug;
      public FileTrace() throws java.io.IOException {
            // a real FileTrace would need to obtain the filename
            // somewhere for the example I'll hardcode it
            pw = new java.io.PrintWriter
                ( new java.io.FileWriter( "c:\trace.log" ) );
      }
      public void setDebug( boolean debug ) {
            this.debug = debug;
      }
      public void debug( String message ) {
            if( debug ) {  // only print if debug is true
                  pw.println( "DEBUG: " + message );
                  pw.flush();
            }
      }
      public void error( String message ) {
            // always print out errors
            pw.println( "ERROR: " + message );
            pw.flush();
      }
}

public class SystemTrace implements Trace {
      private boolean debug;
      public void setDebug( boolean debug ) {
            this.debug = debug;
      }
      public void debug( String message ) {
            if( debug ) {  // only print if debug is true
                  System.out.println( "DEBUG: " + message );
            }
      }
      public void error( String message ) {
            // always print out errors
            System.out.println( "ERROR: " + message );
      }
}

// To use the class
SystemTrace log = new SystemTrace();
log.debug( "entering log" );
Factory Method

// To use factory method
public class TraceFactory {
      public static Trace getTrace() {
            return new SystemTrace();
      }
}
Trace log = new TraceFactory.getTrace();

// A better factory method
public class TraceFactory {
      public static Trace getTrace() {
            try {
                  return new FileTrace();
            } catch ( java.io.IOException ex ) {
                  Trace t = new SystemTrace();
                  t.error( "could not instantiate FileTrace: " 
                          + ex.getMessage() );
                  return t;
            }
      }
}

No comments:

Post a Comment