Skip to content

How to not hardcoding image extensions in Java?

How to not hardcoding image extensions in Java?

            switch(extension) {
                case "zip" -> {
                    FileUtil.saveFile(multipartFile, historyFolder, FileType.ZIP, backupFilePath);
                    FileUtil.saveFile(multipartFile, target, FileType.ZIP, filePath);
                case "jpg", "jpeg", "png", ".bmp", ".svg", "webp", "jfif", "pjpeg", "pjp", "apng", "avif" -> {
                    FileUtil.saveFile(multipartFile, historyFolder, FileType.IMAGE, backupFilePath);
                    FileUtil.saveFile(multipartFile, target, FileType.IMAGE, filePath);
                default -> throw new GlobalCustomException(ErrorCode.ILLIGAL_FILE_TYPE);

Above is my code.

In the case statement, I have listed strings as hard-coded as jpg, jpeg….

This code is not flexible, so I’m sure there must be a better way.

I’d appreciate it if you could give me a solution that I’m not aware of.



As one of possible ways, you can use URLConnection.guessContentTypeFromName() like this.

String mimeType ="test." + extension);
boolean isImage = mimeType != null && mimeType.startWith("image/")

You can add custom extensions to the $JAVA_HOME/jre/lib/ file.

Also see these questions.

User contributions licensed under: CC BY-SA
2 People found this is helpful