Get Filename without Extension in Java

You can get the name of a file without it’s extension in Java by using the FilenameUtils of Apache Commons IO:

1
2
3
4
5
6
7
8
9
10
11
12
import java.io.File;
import org.apache.commons.io.FilenameUtils;
 
public class NewMain
{
  public static void main(String[] args)
  {
    File file = new File("C:/This/is/a/test.txt");
    String fileNameWithOutExtension = FilenameUtils.removeExtension(file.getName());
    System.out.println(fileNameWithOutExtension); // prints 'test'
  }
}

Another approach without using external libraries is:

1
2
3
4
5
6
File file = new File("C:/This/is/a/test.txt");
String fileNameWithOutExtension = file.getName();
int index = fileNameWithOutExtension.lastIndexOf('.');
if (index != -1)
  fileNameWithOutExtension = fileNameWithOutExtension.substring(0, index);
System.out.println(fileNameWithOutExtension); // prints 'test

How to count occurrences of a character in a String with Java?

Code sample:

public class CharacterCounter
{
  public static int countOccurrences(String find, String string)
  {
    int count = 0;
    int indexOf = 0;
 
    while (indexOf > -1)
    {
      indexOf = string.indexOf(find, indexOf + 1);
      if (indexOf > -1)
        count++;
    }
 
    return count;
  }
}

Method call:

int occurrences = CharacterCounter.countOccurrences("l", "Hello World.");
System.out.println(occurrences); // 3

You can also count the occurrences of characters in a string by using the Apache commons lang library with the following one-liner:

int count = StringUtils.countMatches("a.b.c.d", ".");

If you are using the Sping Framework then you can do:

int occurance = StringUtils.countOccurrencesOf("a.b.c.d", ".");

If you want to be really smart (and don’t want to use a loop), then you can also use this one here:

int count = string.length() - string.replace(find, "").length();