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 |
The second approach fails if the file name did not have a ‚.‘ char.
Yes, you’re right. Thank you for pointing that out. I modified the code! 🙂