Skip to content

Instantly share code, notes, and snippets.

@Keshava11
Created December 28, 2016 09:18
Show Gist options
  • Save Keshava11/29d65235064e9bb29890d8d8d2f0f738 to your computer and use it in GitHub Desktop.
Save Keshava11/29d65235064e9bb29890d8d8d2f0f738 to your computer and use it in GitHub Desktop.
File name utility extracted from FileNameUtils class in Apache's IO library
/**
* Simplest utility to fetch the name of file from full path extracted from {@link FileNameUtils} given under below link
* References : https://android.googlesource.com/platform/packages/apps/UnifiedEmail/+/master/src/org/apache/commons/io/FilenameUtils.java
*/
public class FileNameUtils {
/**
* The Unix separator character.
*/
private static final char UNIX_SEPARATOR = '/';
/**
* The Windows separator character.
*/
private static final char WINDOWS_SEPARATOR = '\\';
/**
* Fetches the index of last separator of either UNIX_SEPARATOR or WINDOWS_SEPARATOR
*
* @param filename complete filename
* @return last index of occurrence of either UNIX_SEPARATOR or WINDOWS_SEPARATOR
*/
private static int indexOfLastSeparator(String filename) {
if (filename == null) {
return -1;
}
int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
return Math.max(lastUnixPos, lastWindowsPos);
}
/**
* Gets the name minus the path from a full filename.
* <p>
* This method will handle a file in either Unix or Windows format.
* The text after the last forward or backslash is returned.
* <pre>
* a/b/c.txt --> c.txt
* a.txt --> a.txt
* a/b/c --> c
* a/b/c/ --> ""
* </pre>
* <p>
* The output will be the same irrespective of the machine that the code is running on.
*
* @param filename the filename to query, null returns null
* @return the name of the file without the path, or an empty string if none exists
*/
public static String getName(String filename) {
if (filename == null) {
return null;
}
int index = indexOfLastSeparator(filename);
return filename.substring(index + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment