To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);
A disk designator with a backslash, for example "C:\" or "d:\". A single backslash, for example, "\directory" or "\file. txt". This is also referred to as an absolute path.
File getName() method in Java with Examples The getName() method is a part of File class. This function returns the Name of the given file object. The function returns a string object which contains the Name of the given file object.
In other words, if the user specifies the file name to be "myFile. txt", and that file is already in the current directory: reader = new BufferedReader(new FileReader("myFile. txt"));
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));
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.
Using FilenameUtils
in Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With