Java File Name Get getFileName(String filePath)

Here you can find the source of getFileName(String filePath)

Description

An OS independent getName alternative.

License

Apache License

Parameter

Parameter Description
filePath the file path as a string

Return

the file name, or the complete path of no file name is detected

Declaration

public static String getFileName(String filePath) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    /**//w ww  . j ava 2  s.  c o m
     * An OS independent getName alternative. Useful if the path is provided as
     * a hardcoded string and opened in a different OS.
     *
     * @param filePath the file path as a string
     * @return the file name, or the complete path of no file name is detected
     */
    public static String getFileName(String filePath) {

        String tempFileName = filePath;

        int slash1 = tempFileName.lastIndexOf("/");
        int slash2 = tempFileName.lastIndexOf("\\");

        int lastSlashIndex = Math.max(slash1, slash2);

        if (lastSlashIndex != -1) {
            tempFileName = tempFileName.substring(lastSlashIndex + 1);
        }

        return tempFileName;
    }

    /**
     * An OS independent getName alternative. Useful if the path is provided as
     * a hardcoded string and opened in a different OS.
     *
     * @param file the file
     * @return the file name, or the complete path of no file name is detected
     */
    public static String getFileName(File file) {
        return getFileName(file.getAbsolutePath());
    }
}

Related

  1. getFileName(String absolutePath)
  2. getFileName(String completePath)
  3. getFileName(String dir, String name)
  4. getFileName(String f)
  5. getFileName(String fileName)
  6. getFileName(String filePath)
  7. getFileName(String filepath)
  8. getFileName(String filePath)
  9. getFileName(String filePath)