-1

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.

  • We need more info like; FileUtil what is the package? What is multipartFile, byte[] or something else? Why do you save with FileType? You should normally save anything with any extension without providing de FileType. – sgpalit Oct 11 '22 at 08:00
  • If you want extensibility, maybe you should read about Service Provider Interface(SPI) and implement interfaces for different file types... – Rafael Guillen Oct 11 '22 at 08:08

3 Answers3

1

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

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

You can add custom extensions to the $JAVA_HOME/jre/lib/content-types.properties file.

Also see these questions.

relent95
  • 3,703
  • 1
  • 14
  • 17
0

Maybe you can try using an array with extensions and pass in a case statement. Take all the image formats as a single array element and zip format as another array element.

This should give the nearest logic. https://stackoverflow.com/a/46700392/20191548

Try if it works

0
String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}
extension=fileName.substring(0,i)+"."+extension;
FileUtil.saveFile(multipartFile, historyFolder, extension, backupFilePath); 
FileUtil.saveFile(multipartFile, target, extension, filePath);
Gun Slinger
  • 135
  • 3