在做图片上传,我的项目中遇到了CommonsMultipartFile要转换为File。经过对CommonsMultipartFile源代码的分析发现它有一个方法getInputStream返回类型还是InputStream这就好办了。在此之前用过强转不允许!
直接上代码,问题解决
private static void inputStreamToFile(InputStream ins, File file){
FileOutputStream os=null;
try {
os=new FileOutputStream(file);
int bytesRead=0;
byte[] buffer=new byte[1024];
while ((bytesRead=ins.read(buffer))!=-1){
os.write(buffer,0,bytesRead);
}
}catch (Exception e){
throw new RuntimeException("调用inputStreamToFile产生异常:"+e.getMessage());
}finally {
try {
if (os!=null){
os.close();
}
if (ins!=null){
ins.close();
}
}catch (IOException e){
throw new RuntimeException("inputStreamToFile关闭io产生异常:"+e.getMessage());
}
}
}