How to remove file extension in Java

2 Answers

0 votes
public class FileUtils {

    /**
     * Removes the last file extension from a filename or path.
     *
     * Examples:
     * document.pdf      -> document
     * archive.tar.gz    -> archive.tar
     * photo.jpg         -> photo
     * README            -> README
     * /tmp/file.txt     -> /tmp/file
     *
     * @param path The filename or path.
     * @return The filename/path without its last extension.
     * @throws IllegalArgumentException if path is null.
     */
    public static String removeFileExtension(String path) {
        if (path == null) {
            throw new IllegalArgumentException("Path cannot be null.");
        }

        // Find the position of the last path separator.
        int lastSeparator = Math.max(
            path.lastIndexOf('/'),
            path.lastIndexOf('\\')
        );

        // Find the last dot.
        int lastDot = path.lastIndexOf('.');

        // No extension found.
        if (lastDot == -1) {
            return path;
        }

        // The dot belongs to a directory name, not the file.
        if (lastDot < lastSeparator) {
            return path;
        }

        // Return everything before the extension.
        return path.substring(0, lastDot);
    }

    public static void main(String[] args) {
        System.out.println(removeFileExtension("document.pdf"));
        System.out.println(removeFileExtension("archive.tar.gz"));
        System.out.println(removeFileExtension("/tmp/file.txt"));
        System.out.println(removeFileExtension("README"));
    }
}


/*
run:

document
archive.tar
/tmp/file
README

*/

 



answered 2 days ago by avibootz
0 votes
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtils {

    public static String removeFileExtension(String filename) {
        int lastDot = filename.lastIndexOf('.');
    
        if (lastDot <= 0) {
            return filename;
        }
    
        return filename.substring(0, lastDot);
    }

    public static void main(String[] args) {
        System.out.println(removeFileExtension("document.pdf"));
        System.out.println(removeFileExtension("archive.tar.gz"));
        System.out.println(removeFileExtension("/tmp/file.txt"));
        System.out.println(removeFileExtension("README"));
    }
}


/*
run:

document
archive.tar
/tmp/file
README

*/

 



answered 2 days ago by avibootz
...