整一个工具类【根据URL地址获取file文件对象】
直接将网络url文件转换为file对象
| |
| import java.io.*; |
| import java.net.URL; |
| public class ImgUtils { |
| |
| |
| |
| |
| |
| |
| |
| public static File getImageFileFromUrl(String imageUrl, String savePath) throws Exception { |
| |
| URL url = new URL(imageUrl); |
| InputStream in = url.openStream(); |
| |
| |
| |
| String[] split = imageUrl.split("/"); |
| String fileName = split[split.length - 1]; |
| File file = new File(savePath + fileName); |
| if(!file.exists()) { |
| file.createNewFile(); |
| } |
| |
| |
| FileOutputStream out = new FileOutputStream(file); |
| byte[] buffer = new byte[4096]; |
| int n = 0; |
| while ((n = in.read(buffer)) != -1) { |
| out.write(buffer, 0, n); |
| } |
| out.close(); |
| in.close(); |
| |
| return file; |
| } |
| |
| |
| |
| |
| |
| |
| |
| private static File getFileByHttpURL(String path){ |
| String newUrl = path.split("[?]")[0]; |
| String[] suffix = newUrl.split("/"); |
| |
| String fileName = suffix[suffix.length - 1]; |
| File file = null; |
| InputStream inputStream = null; |
| OutputStream outputStream = null; |
| try{ |
| file = File.createTempFile("report",fileName); |
| URL urlFile = new URL(newUrl); |
| inputStream = urlFile.openStream(); |
| outputStream = new FileOutputStream(file); |
| |
| int bytesRead = 0; |
| byte[] buffer = new byte[8192]; |
| while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) { |
| outputStream.write(buffer, 0, bytesRead); |
| } |
| }catch (Exception e) { |
| e.printStackTrace(); |
| }finally { |
| try { |
| if (null != outputStream) { |
| outputStream.close(); |
| } |
| if (null != inputStream) { |
| inputStream.close(); |
| } |
| |
| } catch (Exception e) { |
| e.printStackTrace(); |
| } |
| } |
| return file; |
| } |
| |
| public static void main(String[] args) throws Exception { |
| |
| File file = ImgUtils.getFileByHttpURL("【你的图片网络url】"); |
| System.out.println("file.length() = " + file.length()); |
| } |
| } |
| |