我已经编写了一个这样的方法.但我想这应该重构.
任何人可以建议避免使用这个多个if语句的最佳方法?
任何人可以建议避免使用这个多个if语句的最佳方法?
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"; }
我不能在这里使用switch-case,因为我的’condition’是一个java.lang.String.
解决方法
您可以使用
Map
来保存您的解决方案:
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; } }
为使该代码工作,你需要定义NO_EXTENSION_MIME_TYPE和UNKNOWN_EXTENSION_MIME_TYPE在你的课,有点像这样:
private static final String NO_EXTENSION_MIME_TYPE = "application/octet-stream"; private static final String UNKNOWN_EXTENSION_MIME_TYPE = "text/plain";