Code example for OutputStream

Methods: close, flush, write

0
   *          are rethrown to caller 
   */ 
  public void finishPingFile() throws Exception { 
    try { 
      byte[] footer = makePingFooter(checksum);
      outputStream.write(footer);
      // We're done writing, so force the stream to flush the buffer. 
      outputStream.flush();
      Logger.debug(LOG_TAG, "Wrote " + footer.length + " footer bytes.");
    } catch (UnsupportedEncodingException e) {
      cleanUpAndRethrow("Checksum encoding exception", e);
    } catch (IOException e) {
      cleanUpAndRethrow("Error writing footer to stream", e);
    } finally { 
      try { 
        outputStream.close();
      } catch (IOException e) {
        // Failed to close, nothing we can do except discard the reference to the stream. 
        outputStream = null;
      } 
    } 
 
    // Move temp file to destination specified by caller. 
    try { 
      File destFile = new File(parentDir, filename);
      // Delete file if it exists - docs state that rename may fail if the File already exists. 
      if (destFile.exists()) {
        destFile.delete();
      } 
      boolean result = tmpFile.renameTo(destFile);
      if (!result) {
        throw new IOException("Could not move tmp file to destination.");
      } 
    } finally { 
      cleanUp(); 
    } 
  } 
 
  private byte[] makePingFooter(MessageDigest checksum)
      throws UnsupportedEncodingException { 
    base64Checksum = Base64.encodeToString(checksum.digest(), Base64.NO_WRAP);
    return ("\",\"checksum\":" + JSONObject.quote(base64Checksum) + "}")
        .getBytes(charset);
  } 
 
  /** 
   * Get final digested Base64 checksum. 
   * 
   * @return String checksum if it has been calculated, null otherwise. 
   */ 
  protected String getFinalChecksum() {
    return base64Checksum;
  } 
 
  public String getCharset() {
    return this.charset;
  } 
 
  /** 
   * Clean up checksum and delete the temporary file. 
   */ 
  private void cleanUp() { 
    // Discard checksum. 
    checksum.reset();
 
    // Clean up files. 
    if (tmpFile != null && tmpFile.exists()) {
      tmpFile.delete();
    } 
    tmpFile = null;
  } 
 
  /** 
   * Log message and error and clean up, then rethrow exception to caller. 
   * 
   * @param message 
   *          Error message 
   * @param e 
   *          Exception 
   * 
   * @throws Exception 
   *           Exception to be rethrown to caller 
   */ 
  private void cleanUpAndRethrow(String message, Exception e) throws Exception {
    Logger.error(LOG_TAG, message, e);
    cleanUp(); 
 
    if (outputStream != null) {
      try { 
        outputStream.close();
      } catch (IOException exception) {
        // Failed to close stream; nothing we can do, and we're aborting anyways. 
      } 
    }