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.
CodePudding user response:
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.
CodePudding user response:
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
CodePudding user response:
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);