Code example for File

Methods: createNewFile, delete, exists

0
    // Open stream to temporary file for writing. 
    try { 
      tmpFile = File.createTempFile(filename, "tmp", cacheDir);
    } catch (IOException e) {
      // Try to create the temporary file in the ping directory. 
      tmpFile = new File(parentDir, filename + ".tmp");
      try { 
        tmpFile.createNewFile();
      } catch (IOException e1) {
        cleanUpAndRethrow("Failed to create tmp file in temp directory or ping directory.", e1);
      } 
    } 
 
    try { 
      if (blockSize > 0) {
        outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile), blockSize);
      } else { 
        outputStream = new BufferedOutputStream(new FileOutputStream(tmpFile));
      } 
 
      // Create checksum for ping. 
      checksum = MessageDigest.getInstance("SHA-256");
 
      // Write ping header. 
      byte[] header = makePingHeader(filename);
      outputStream.write(header);
      Logger.debug(LOG_TAG, "Wrote " + header.length + " header bytes.");
 
    } catch (NoSuchAlgorithmException e) {
      cleanUpAndRethrow("Error creating checksum digest", e);
    } catch (UnsupportedEncodingException e) {
      cleanUpAndRethrow("Error writing header", e);
    } catch (IOException e) {
      cleanUpAndRethrow("Error writing to stream", e);
    } 
  } 
 
  private byte[] makePingHeader(String slug)
      throws UnsupportedEncodingException { 
    return ("{\"slug\":" + JSONObject.quote(slug) + "," + "\"payload\":\"")
        .getBytes(charset);
  } 
 
  /** 
   * Append payloadContent to ping file and update the checksum. 
   * 
   * @param payloadContent 
   *          String content to be written 
   * @return number of bytes written, or -1 if writing failed 
   * @throws Exception 
   *           Checked exceptions <code>UnsupportedEncodingException</code> or 
   *           <code>IOException</code> and unchecked exception that 
   *           are rethrown to caller 
   */ 
  public int appendPayload(String payloadContent) throws Exception {
    if (payloadContent == null) {
      cleanUpAndRethrow("Payload is null", new Exception());
      return -1; 
    } 
 
    try { 
      byte[] payloadBytes = payloadContent.getBytes(charset);
      // If we run into an error, we'll throw and abort, so checksum won't be stale. 
      checksum.update(payloadBytes);
 
      byte[] quotedPayloadBytes = JSONObject.quote(payloadContent).getBytes(charset);
 
      // First and last bytes are quotes inserted by JSONObject.quote; discard 
      // them. 
      int numBytes = quotedPayloadBytes.length - 2;
      outputStream.write(quotedPayloadBytes, 1, numBytes);
      return numBytes;
 
    } catch (UnsupportedEncodingException e) {
      cleanUpAndRethrow("Error encoding payload", e);
      return -1; 
    } catch (IOException e) {
      cleanUpAndRethrow("Error writing to stream", e);
      return -1; 
    } 
  } 
 
  /** 
   * Add the checksum of the payload to the ping file and close the stream. 
   * 
   * @throws Exception 
   *          Checked exceptions <code>UnsupportedEncodingException</code> or 
   *          <code>IOException</code> and unchecked exception that 
   *          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;
  } 
 
  /**