339

Can anyone tell me how to get the filename without the extension? Example:

fileNameWithExt = "test.xml";
fileNameWithOutExt = "test";
james.garriss
  • 12,959
  • 7
  • 83
  • 96
Iso
  • 3,668
  • 2
  • 20
  • 18
  • Possible duplicate of [How to get file name from file path in android](http://stackoverflow.com/questions/26570084/how-to-get-file-name-from-file-path-in-android) – Emil Heraña May 02 '17 at 11:29

22 Answers22

522

If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in null or dots in the path but not in the filename, you can use the following:

import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
jacksondc
  • 600
  • 1
  • 6
  • 19
Ulf Lindback
  • 13,974
  • 3
  • 40
  • 31
  • 87
    you can also use FilenameUtils.getBasename to go straight from a path string to a filename-without-extension. – Ian Durkan Jan 28 '11 at 16:37
  • Where do you get the `.jar` for this? – Andrew Wyld Dec 29 '12 at 13:50
  • 2
    The easiest is of course running maven :-) Otherwise see: http://commons.apache.org/io/ – Ulf Lindback Jan 02 '13 at 13:48
  • 9
    For those who prefer Guava, [it can do this too](http://stackoverflow.com/a/15923609/56285). (These days I don't personally feel very good about adding Apache Commons dependencies, though historically those libraries have been very useful.) – Jonik Apr 10 '13 at 10:48
  • 3
    While Guava and Commons-IO may offer a little extra, you'd be surprised how many convenience methods are already **included in JDK 7** with `java.nio.file.Files` and `Path` -- such as resolving base directories, one-line copying/moving files, getting only the file name etc. – Don Cheadle Feb 19 '15 at 20:13
  • 5
    @Lan Durkan currently FilenameUtils.getBaseName with capital N – Slow Harry Aug 11 '16 at 12:21
  • How come `FilenameUtils` isn't available when using this version: `implementation 'commons-io:commons-io:20030203.000550'` ? Was it replaced with something else? – android developer May 21 '19 at 08:23
  • @androiddeveloper this version is from 2005, too old, check here https://mvnrepository.com/artifact/commons-io/commons-io – Felipe Aug 15 '19 at 07:02
188

The easiest way is to use a regular expression.

fileNameWithOutExt = "test.xml".replaceFirst("[.][^.]+$", "");

The above expression will remove the last dot followed by one or more characters. Here's a basic unit test.

public void testRegex() {
    assertEquals("test", "test.xml".replaceFirst("[.][^.]+$", ""));
    assertEquals("test.2", "test.2.xml".replaceFirst("[.][^.]+$", ""));
}
brianegge
  • 29,240
  • 13
  • 74
  • 99
  • 12
    Regex is not as easy to use as the library solution above. It works, but looking at the code (without having to interpret the REGEX) isn't obvious what it does. – Gustavo Litovsky Nov 28 '12 at 21:12
  • 5
    @GustavoLitovsky Android doesn't come bundled with `org.apache.commons`. As far as I'm aware, this is the only way to do it in Android. – Liam George Betsworth Jun 06 '14 at 08:56
  • 1
    /* the following regex also removes path */ "/the/path/name.extension".replaceAll(".*[\\\\/]|\\.[^\\.]*$",""); – daggett Feb 19 '15 at 10:06
  • 1
    I would add slashes to the second character class to ensure that you're not tripped up by a path like "/foo/bar.x/baz" – chrisinmtown Jul 17 '15 at 12:10
  • 1
    To not have to worry about paths create `File` object then `getName` on it and then use this regex. – Paramvir Singh Karwal Apr 26 '21 at 05:19
  • Thanks. I'm in company where it is forbidden to use all the apache.commons utils. I do not understand why!!.. Or I'm not agree with this. – fayabobo Jun 03 '22 at 10:26
80

Here is the consolidated list order by my preference.

Using apache commons

import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
                          
                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

Using Google Guava (If u already using it)

import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);

Files.getNameWithoutExtension

Or using Core Java

1)

String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
    fileName = fileName.substring(0, pos);
}
if (fileName.indexOf(".") > 0) {
   return fileName.substring(0, fileName.lastIndexOf("."));
} else {
   return fileName;
}
private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");

public static String getFileNameWithoutExtension(File file) {
    return ext.matcher(file.getName()).replaceAll("");
}

Liferay API

import com.liferay.portal.kernel.util.FileUtil; 
String fileName = FileUtil.stripExtension(file.getName());
Reinhold
  • 546
  • 1
  • 3
  • 14
Om.
  • 2,532
  • 4
  • 22
  • 22
57

See the following test program:

public class javatemp {
    static String stripExtension (String str) {
        // Handle null case specially.

        if (str == null) return null;

        // Get position of last '.'.

        int pos = str.lastIndexOf(".");

        // If there wasn't any '.' just return the string as is.

        if (pos == -1) return str;

        // Otherwise return the string, up to the dot.

        return str.substring(0, pos);
    }

    public static void main(String[] args) {
        System.out.println ("test.xml   -> " + stripExtension ("test.xml"));
        System.out.println ("test.2.xml -> " + stripExtension ("test.2.xml"));
        System.out.println ("test       -> " + stripExtension ("test"));
        System.out.println ("test.      -> " + stripExtension ("test."));
    }
}

which outputs:

test.xml   -> test
test.2.xml -> test.2
test       -> test
test.      -> test
Ontonator
  • 319
  • 3
  • 17
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
46

If your project uses Guava (14.0 or newer), you can go with Files.getNameWithoutExtension().

(Essentially the same as FilenameUtils.removeExtension() from Apache Commons IO, as the highest-voted answer suggests. Just wanted to point out Guava does this too. Personally I didn't want to add dependency to Commons—which I feel is a bit of a relic—just because of this.)

Community
  • 1
  • 1
Jonik
  • 80,077
  • 70
  • 264
  • 372
10

Below is reference from https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java

/**
 * Gets the base name, without extension, of given file name.
 * <p/>
 * e.g. getBaseName("file.txt") will return "file"
 *
 * @param fileName
 * @return the base name
 */
public static String getBaseName(String fileName) {
    int index = fileName.lastIndexOf('.');
    if (index == -1) {
        return fileName;
    } else {
        return fileName.substring(0, index);
    }
}
chubao
  • 5,871
  • 6
  • 39
  • 64
7

If you don't like to import the full apache.commons, I've extracted the same functionality:

public class StringUtils {
    public static String getBaseName(String filename) {
        return removeExtension(getName(filename));
    }

    public static int indexOfLastSeparator(String filename) {
        if(filename == null) {
            return -1;
        } else {
            int lastUnixPos = filename.lastIndexOf(47);
            int lastWindowsPos = filename.lastIndexOf(92);
            return Math.max(lastUnixPos, lastWindowsPos);
        }
    }

    public static String getName(String filename) {
        if(filename == null) {
            return null;
        } else {
            int index = indexOfLastSeparator(filename);
            return filename.substring(index + 1);
        }
    }

    public static String removeExtension(String filename) {
        if(filename == null) {
            return null;
        } else {
            int index = indexOfExtension(filename);
            return index == -1?filename:filename.substring(0, index);
        }
    }

    public static int indexOfExtension(String filename) {
        if(filename == null) {
            return -1;
        } else {
            int extensionPos = filename.lastIndexOf(46);
            int lastSeparator = indexOfLastSeparator(filename);
            return lastSeparator > extensionPos?-1:extensionPos;
        }
    }
}
Hamzeh Soboh
  • 7,572
  • 5
  • 43
  • 54
6

For Kotlin it's now simple as:

val fileNameStr = file.nameWithoutExtension
Tareq Joy
  • 342
  • 3
  • 12
5

While I am a big believer in reusing libraries, the org.apache.commons.io JAR is 174KB, which is noticably large for a mobile app.

If you download the source code and take a look at their FilenameUtils class, you can see there are a lot of extra utilities, and it does cope with Windows and Unix paths, which is all lovely.

However, if you just want a couple of static utility methods for use with Unix style paths (with a "/" separator), you may find the code below useful.

The removeExtension method preserves the rest of the path along with the filename. There is also a similar getExtension.

/**
 * Remove the file extension from a filename, that may include a path.
 * 
 * e.g. /path/to/myfile.jpg -> /path/to/myfile 
 */
public static String removeExtension(String filename) {
    if (filename == null) {
        return null;
    }

    int index = indexOfExtension(filename);

    if (index == -1) {
        return filename;
    } else {
        return filename.substring(0, index);
    }
}

/**
 * Return the file extension from a filename, including the "."
 * 
 * e.g. /path/to/myfile.jpg -> .jpg
 */
public static String getExtension(String filename) {
    if (filename == null) {
        return null;
    }

    int index = indexOfExtension(filename);

    if (index == -1) {
        return filename;
    } else {
        return filename.substring(index);
    }
}

private static final char EXTENSION_SEPARATOR = '.';
private static final char DIRECTORY_SEPARATOR = '/';

public static int indexOfExtension(String filename) {

    if (filename == null) {
        return -1;
    }

    // Check that no directory separator appears after the 
    // EXTENSION_SEPARATOR
    int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);

    int lastDirSeparator = filename.lastIndexOf(DIRECTORY_SEPARATOR);

    if (lastDirSeparator > extensionPos) {
        LogIt.w(FileSystemUtil.class, "A directory separator appears after the file extension, assuming there is no file extension");
        return -1;
    }

    return extensionPos;
}
Dan J
  • 25,433
  • 17
  • 100
  • 173
3
fileEntry.getName().substring(0, fileEntry.getName().lastIndexOf("."));
4b0
  • 21,981
  • 30
  • 95
  • 142
3

Given the String filename, you can do:

String filename = "test.xml";
filename.substring(0, filename.lastIndexOf("."));   // Output: test
filename.split("\\.")[0];   // Output: test
2

Simplest way to get name from relative path or full path is using

import org.apache.commons.io.FilenameUtils; FilenameUtils.getBaseName(definitionFilePath)

2

You can use java split function to split the filename from the extension, if you are sure there is only one dot in the filename which for extension.

File filename = new File('test.txt'); File.getName().split("[.]");

so the split[0] will return "test" and split[1] will return "txt"

Danish Ahmed
  • 490
  • 5
  • 6
  • 3
    What if the file contains multiple '.' in such case this method will give an unexpected results. – Vijay Aug 24 '20 at 08:49
1
public static String getFileExtension(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static String getBaseFileName(String fileName) {
        if (TextUtils.isEmpty(fileName) || !fileName.contains(".") || fileName.endsWith(".")) return null;
        return fileName.substring(0,fileName.lastIndexOf("."));
    }
Gil SH
  • 3,789
  • 1
  • 27
  • 25
1

Use FilenameUtils.removeExtension from Apache Commons IO

Example:

You can provide full path name or only the file name.

String myString1 = FilenameUtils.removeExtension("helloworld.exe"); // returns "helloworld"
String myString2 = FilenameUtils.removeExtension("/home/abc/yey.xls"); // returns "yey"

Hope this helps ..

Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
1

The fluent way:

public static String fileNameWithOutExt (String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .filter(i-> i > fileName.lastIndexOf(File.separator))
            .map(i-> fileName.substring(0, i)).orElse(fileName);
}
Nolle
  • 201
  • 2
  • 5
0

You can split it by "." and on index 0 is file name and on 1 is extension, but I would incline for the best solution with FileNameUtils from apache.commons-io like it was mentioned in the first article. It does not have to be removed, but sufficent is:

String fileName = FilenameUtils.getBaseName("test.xml");

Peter S.
  • 470
  • 1
  • 7
  • 17
0

Keeping it simple, use Java's String.replaceAll() method as follows:

String fileNameWithExt = "test.xml";
String fileNameWithoutExt
   = fileNameWithExt.replaceAll( "^.*?(([^/\\\\\\.]+))\\.[^\\.]+$", "$1" );

This also works when fileNameWithExt includes the fully qualified path.

gwc
  • 1,273
  • 7
  • 12
0

My solution needs the following import.

import java.io.File;

The following method should return the desired output string:

private static String getFilenameWithoutExtension(File file) throws IOException {
    String filename = file.getCanonicalPath();
    String filenameWithoutExtension;
    if (filename.contains("."))
        filenameWithoutExtension = filename.substring(filename.lastIndexOf(System.getProperty("file.separator"))+1, filename.lastIndexOf('.'));
    else
        filenameWithoutExtension = filename.substring(filename.lastIndexOf(System.getProperty("file.separator"))+1);

    return filenameWithoutExtension;
}
0

com.google.common.io.Files

Files.getNameWithoutExtension(sourceFile.getName())

can do a job as well

Maksim Sirotkin
  • 473
  • 2
  • 5
  • 14
0

file name only, where full path is also included. No need for external libs, regex...etc

    public class MyClass {
    public static void main(String args[]) {
  
  
      String file  = "some/long/directory/blah.x.y.z.m.xml";

      System.out.println(file.substring(file.lastIndexOf("/") + 1, file.lastIndexOf(".")));
     //outputs blah.x.y.z.m
    }

}
z atef
  • 7,138
  • 3
  • 55
  • 50
-3

Try the code below. Using core Java basic functions. It takes care of Strings with extension, and without extension (without the '.' character). The case of multiple '.' is also covered.

String str = "filename.xml";
if (!str.contains(".")) 
    System.out.println("File Name=" + str); 
else {
    str = str.substring(0, str.lastIndexOf("."));
    // Because extension is always after the last '.'
    System.out.println("File Name=" + str);
}

You can adapt it to work with null strings.

andr
  • 15,970
  • 10
  • 45
  • 59
Sksoni
  • 25
  • 1
  • 1
    It's pretty bad practise to implement this kind of functionality yourself. On the first glance the task seems to be **extremely obvious**, but in practise you will face a lot of *exceptional* situations (like there is no `.` in file name, or file is a backup and has name like `document.docx.backup`, etc). It's much more reliable to use external library which deals with all this exceptional situations for you. – ivstas Jun 06 '14 at 09:29
  • 1
    On the other hand adding to many libraries to your project will make it larger. So simple things like this could be done by yourself. – string.Empty Nov 25 '14 at 08:48
  • 1
    No way you should do this yourself. This is hard: files with no extension but . in path, ftp paths, windows and unix slashes, symbolic links etc... You will certainly fail and by trying to gain a bit of memory you will ad a lot of unstability. At the minimum copy the sources of established code if licences permit it. – Jonathan Nappee Nov 30 '15 at 21:22
  • This code looks like the one from Amit Mishra, except for that intimidating 'if (!str.contains("."))' – Broken_Window Apr 13 '16 at 21:46
  • would fail in the following case "/someFolder/some.other.folder/someFileWithoutExtention". First thing that popped in mind after 2 seconds.. i'm sure I could come up with a ton load of other examples. – Newtopian Sep 26 '16 at 19:20
  • I do not clearly see the relation among those comment (ivstas, Nicolas & Jonathan), answer and question. The question was about a file and not path first. Second, I do not see an additional library in this code. Can someone tell what is going on, please? – Jaja Nov 14 '20 at 13:34