How do I get the file name from a String containing the Absolute file path?

JavaFileFilenamesFilepath

Java Problem Overview


String variable contains a file name, C:\Hello\AnotherFolder\The File Name.PDF. How do I only get the file name The File Name.PDF as a String?

I planned to split the string, but that is not the optimal solution.

Java Solutions


Solution 1 - Java

just use File.getName()

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());

using String methods:

  File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");  
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));
    	

Solution 2 - Java

Alternative using Path (Java 7+):

Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();

Note that splitting the string on \\ is platform dependent as the file separator might vary. Path#getName takes care of that issue for you.

Solution 3 - Java

Using FilenameUtils in Apache Commons IO :

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");

Solution 4 - Java

Considering the String you're asking about is

C:\Hello\AnotherFolder\The File Name.PDF

we need to extract everything after the last separator, ie. \. That is what we are interested in.

You can do

String fullPath = "C:\\Hello\\AnotherFolder\\The File Name.PDF";
int index = fullPath.lastIndexOf("\\");
String fileName = fullPath.substring(index + 1);

This will retrieve the index of the last \ in your String and extract everything that comes after it into fileName.

If you have a String with a different separator, adjust the lastIndexOf to use that separator. (There's even an overload that accepts an entire String as a separator.)

I've omitted it in the example above, but if you're unsure where the String comes from or what it might contain, you'll want to validate that the lastIndexOf returns a non-negative value because the Javadoc states it'll return

> -1 if there is no such occurrence

Solution 5 - Java

Since 1.7

    Path p = Paths.get("c:\\temp\\1.txt");
    String fileName = p.getFileName().toString();
    String directory = p.getParent().toString();

Solution 6 - Java

you can use path = C:\Hello\AnotherFolder\TheFileName.PDF

String strPath = path.substring(path.lastIndexOf("\\")+1, path.length());

Solution 7 - Java

The other answers didn't quite work for my specific scenario, where I am reading paths that have originated from an OS different to my current one. To elaborate I am saving email attachments saved from a Windows platform on a Linux server. The filename returned from the JavaMail API is something like 'C:\temp\hello.xls'

The solution I ended up with:

String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];

Solution 8 - Java

Considere the case that Java is Multiplatform:

int lastPath = fileName.lastIndexOf(File.separator);
if (lastPath!=-1){
    fileName = fileName.substring(lastPath+1);
}

Solution 9 - Java

A method without any dependency and takes care of .. , . and duplicate separators.

public static String getFileName(String filePath) {
	if( filePath==null || filePath.length()==0 )
		return "";
	filePath = filePath.replaceAll("[/\\\\]+", "/");
	int len = filePath.length(),
		upCount = 0;
	while( len>0 ) {
		//remove trailing separator
		if( filePath.charAt(len-1)=='/' ) {
			len--;
			if( len==0 )
				return "";
		}
		int lastInd = filePath.lastIndexOf('/', len-1);
		String fileName = filePath.substring(lastInd+1, len);
		if( fileName.equals(".") ) {
			len--;
		}
		else if( fileName.equals("..") ) {
			len -= 2;
			upCount++;
		}
		else {
			if( upCount==0 )
				return fileName;
			upCount--;
			len -= fileName.length();
		}
	}
	return "";
}

Test case:

@Test
public void testGetFileName() {
	assertEquals("", getFileName("/"));
	assertEquals("", getFileName("////"));
	assertEquals("", getFileName("//C//.//../"));
	assertEquals("", getFileName("C//.//../"));
	assertEquals("C", getFileName("C"));
	assertEquals("C", getFileName("/C"));
	assertEquals("C", getFileName("/C/"));
	assertEquals("C", getFileName("//C//"));
	assertEquals("C", getFileName("/A/B/C/"));
	assertEquals("C", getFileName("/A/B/C"));
	assertEquals("C", getFileName("/C/./B/../"));
	assertEquals("C", getFileName("//C//./B//..///"));
	assertEquals("user", getFileName("/user/java/.."));
	assertEquals("C:", getFileName("C:"));
	assertEquals("C:", getFileName("/C:"));
	assertEquals("java", getFileName("C:\\Program Files (x86)\\java\\bin\\.."));
	assertEquals("C.ext", getFileName("/A/B/C.ext"));
	assertEquals("C.ext", getFileName("C.ext"));
}

Maybe getFileName is a bit confusing, because it returns directory names also. It returns the name of file or last directory in a path.

Solution 10 - Java

getFileName() method of java.nio.file.Path used to return the name of the file or directory pointed by this path object.

Path getFileName()

For reference:

https://www.geeksforgeeks.org/path-getfilename-method-in-java-with-examples/

Solution 11 - Java

extract file name using java regex *.

public String extractFileName(String fullPathFile){
		try {
			Pattern regex = Pattern.compile("([^\\\\/:*?\"<>|\r\n]+$)");
			Matcher regexMatcher = regex.matcher(fullPathFile);
			if (regexMatcher.find()){
				return regexMatcher.group(1);
			}
		} catch (PatternSyntaxException ex) {
			LOG.info("extractFileName::pattern problem <"+fullPathFile+">",ex);
		}
		return fullPathFile;
	}

Solution 12 - Java

You can use FileInfo object to get all information of your file.

    FileInfo f = new FileInfo(@"C:\Hello\AnotherFolder\The File Name.PDF");
    MessageBox.Show(f.Name);
    MessageBox.Show(f.FullName);
    MessageBox.Show(f.Extension );
    MessageBox.Show(f.DirectoryName);

Solution 13 - Java

This answer works for me in c#:

using System.IO;
string fileName = Path.GetFileName("C:\Hello\AnotherFolder\The File Name.PDF");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSharon WatinsanView Question on Stackoverflow
Solution 1 - JavaPermGenErrorView Answer on Stackoverflow
Solution 2 - JavaassyliasView Answer on Stackoverflow
Solution 3 - JavaBinoy BabuView Answer on Stackoverflow
Solution 4 - JavaSotirios DelimanolisView Answer on Stackoverflow
Solution 5 - Javamax3dView Answer on Stackoverflow
Solution 6 - JavaRakeshView Answer on Stackoverflow
Solution 7 - JavajavaPhobicView Answer on Stackoverflow
Solution 8 - JavaAlejandro HdzView Answer on Stackoverflow
Solution 9 - JavayavuzkavusView Answer on Stackoverflow
Solution 10 - JavaStoneView Answer on Stackoverflow
Solution 11 - JavaHJKView Answer on Stackoverflow
Solution 12 - JavaBlue PhoenixView Answer on Stackoverflow
Solution 13 - JavacgalindoView Answer on Stackoverflow