Avoid multiple if statements in Java

I have written such a method But I think it should be refactored

private String getMimeType(String fileName){
  if(fileName == null) {
    return "";   
  } 
  if(fileName.endsWith(".pdf")) {
    return "application/pdf";   
  }
  if(fileName.endsWith(".doc")) {
    return "application/msword";  
  }
  if(fileName.endsWith(".xls")) {
    return "application/vnd.ms-excel"; 
  }
  if(fileName.endsWith(".xlw")) {
    return "application/vnd.ms-excel"; 
  }
  if(fileName.endsWith(".ppt")) {
    return "application/vnd.ms-powerpoint"; 
  }
  if(fileName.endsWith(".mdb")) {
    return "application/x-msaccess"; 
  }
  if(fileName.endsWith(".rtf")) {
    return "application/rtf"; 
  }
  if(fileName.endsWith(".txt")) {
    return "txt/plain"; 
  }
  if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
    return "txt/html"; 
  }
  return "txt/plain"; 
}

I can't use switch case here because my 'condition' is a Java lang.String.

Solution

You can use map to save your solution:

Map<String,String> extensionToMimeType = new HashMap<String,String>();
extensionToMimeType.put("pdf","application/pdf");
extensionToMimeType.put("doc","application/msword");
// and the rest

int lastDot = fileName.lastIndexOf(".");
String mimeType;
if (lastDot==-1) {
    mimeType = NO_EXTENSION_MIME_TYPE;
} else {
    String extension = fileName.substring(lastDot+1);
    mimeType = extensionToMimeType.get(extension);
    if (mimeType == null) {
        mimeType = UNKNowN_EXTENSION_MIME_TYPE;
    }
}

For this code to work, you need to define No_ EXTENSION_ MIME_ Type and unknown_ EXTENSION_ MIME_ Type in your class, it's a little like this:

private static final String NO_EXTENSION_MIME_TYPE = "application/octet-stream";
private static final String UNKNowN_EXTENSION_MIME_TYPE = "text/plain";
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>