get Extension from String path or File - Android java.io

Android examples for java.io:File Name

Description

get Extension from String path or File

Demo Code

import java.io.File;

import android.text.TextUtils;

public class Main {

  /**/*from ww  w  .j av  a2 s . c  o  m*/
   * Retrieve the main file name.
   * 
   * @param path
   *          the file name.
   * @return the extension of the file.
   */
  public static String getExtension(final String path) {
    if (TextUtils.isEmpty(path)) {
      return null;
    }
    return getExtension(new File(path));
  }

  /**
   * Retrieve the extension of the file.
   * 
   * @param file
   *          the file.
   * @return the extension of the file.
   */
  public static String getExtension(final File file) {
    if (null == file) {
      return null;
    }
    final String fileName = file.getName();
    final int index = fileName.lastIndexOf('.');
    String extension;
    if (index >= 0) {
      extension = fileName.substring(index + 1);
    } else {
      extension = "";
    }
    return extension;
  }

}

Related Tutorials