get Path Without File name - Android java.io

Android examples for java.io:File Path

Description

get Path Without File name

Demo Code

import java.io.File;

public class Main {

  /**/*from ww  w . ja  v  a 2s.c  o  m*/
   * Returns the path only (without file name).
   *
   * @param file
   * @return
   */
  public static File getPathWithoutFilename(File file) {
    if (file != null) {
      if (file.isDirectory()) {
        // no file to be split off. Return everything
        return file;
      } else {
        String filename = file.getName();
        String filepath = file.getAbsolutePath();

        // Construct path without file name.
        String pathwithoutname = filepath.substring(0, filepath.length() - filename.length());
        if (pathwithoutname.endsWith("/")) {
          pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
        }
        return new File(pathwithoutname);
      }
    }
    return null;
  }

}

Related Tutorials