public String getTypeName(String url) { try { String type = FileTypeUtil.getType(new URL(url).openStream()); switch (type) { case "jpg": case "png": case "gif": case "tif": case "bmp": case "dwg": case "rft": case "psd": return "type_img"; case "rmvb": case "flv": case "mp4": case "mpg": case "wmv": case "wav": case "avi": return "type_video"; default: return "type_pdf"; } } catch (Exception e) { e.printStackTrace(); log.error("未找到对应的文件类型!"); } return null; }
时间: 2024-02-10 16:06:45 浏览: 73
Android离线缓存的实例代码
这段代码看起来已经很简洁了,但是可以考虑以下几个优化点:
1. 可以将常量字符串提取成静态常量,避免多次创建字符串对象:
```
private static final String TYPE_IMG = "type_img";
private static final String TYPE_VIDEO = "type_video";
private static final String TYPE_PDF = "type_pdf";
```
2. 可以使用枚举类型代替字符串类型,提高代码的可读性和可维护性:
```
public enum FileType {
JPG, PNG, GIF, TIF, BMP, DWG, RFT, PSD, RMVB, FLV, MP4, MPG, WMV, WAV, AVI, PDF
}
public String getTypeName(String url) {
try {
String type = FileTypeUtil.getType(new URL(url).openStream());
FileType fileType = FileType.valueOf(type.toUpperCase());
switch (fileType) {
case JPG:
case PNG:
case GIF:
case TIF:
case BMP:
case DWG:
case RFT:
case PSD:
return TYPE_IMG;
case RMVB:
case FLV:
case MP4:
case MPG:
case WMV:
case WAV:
case AVI:
return TYPE_VIDEO;
default:
return TYPE_PDF;
}
} catch (Exception e) {
e.printStackTrace();
log.error("未找到对应的文件类型!");
}
return null;
}
```
3. 可以使用异常捕获的多态性,避免不必要的异常类型判断:
```
public String getTypeName(String url) throws IOException {
try (InputStream inputStream = new URL(url).openStream()) {
FileType fileType = FileTypeUtil.getType(inputStream);
switch (fileType) {
case JPG:
case PNG:
case GIF:
case TIF:
case BMP:
case DWG:
case RFT:
case PSD:
return TYPE_IMG;
case RMVB:
case FLV:
case MP4:
case MPG:
case WMV:
case WAV:
case AVI:
return TYPE_VIDEO;
default:
return TYPE_PDF;
}
} catch (IOException e) {
e.printStackTrace();
log.error("未找到对应的文件类型!");
throw e;
}
}
```
希望这些优化点能帮到您!
阅读全文