Once an object's member variables have been populated, the object's encode method can be invoked to encode the value. The general procedure to do this involves the following three steps:
Create an output stream object into which the value will be encoded
Invoke the encode method
Close the output stream.
The first step is the creation of an output stream object. There are two forms of the constructor: a constructor with one parameter (OutputStream reference) and one that allows specification of an internal buffer size. A larger internal buffer size generally provides better performance at the expense of increased memory consumption. The first constructor sets the value to a reasonable mid-range value.
The second step is the invocation of the encode method. The calling arguments were described earlier. As per the Java standard, this method must be invoked from within a try/catch block to catch the possible Asn1Exception and java.io.IOException, which may be thrown. Alternatively, the method from which the encode method is called can declare that it throws Asn1Exception and java.io.IOException leaving it to be dealt with at a higher level.
Finally, close the output stream.
A complete example showing how to invoke a stream-based encode method is as follows:
// Note: personnelRecord object was previously populated with data Asn1BerOutputStream out = null; try { // Step 1: Create an output stream object. This object uses the // default size increment for buffer expansion.. out = new Asn1BerOutputStream (new FileOutputStream (filename)); // Step 2: Invoke the encode method. Note that it must be done // from within a try/catch block.. personnelRecord.encode (out, true); if (trace) { System.out.println ("Encoding was successful"); System.out.println ("Hex dump of encoded record:"); encodeBuffer.hexDump (); System.out.println ("Binary dump:"); encodeBuffer.binDump (); } } catch (Exception e) { System.out.println (e.getMessage()); e.printStackTrace(); return; } finally { // Step 3: Close the output stream, if opened try { if (out != null) out.close (); } catch (Exception e) {} }
If you compare this example with the BER encoding example in Figure 2, you will see the encoding procedure is almost identical. This makes it very easy to switch encoding methods should the need arise. All you need to do is change Asn1BerEncodeBuffer to Asn1BerOutputStream and remove the explicit code that writes the messages into the stream. Also closing of the stream should be added.