一、功能需求
系统需要根据提供的文件地址URL获取该文件,代码实现如下:
二、解决办法
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; }
来源地址:https://blog.csdn.net/qq_37844454/article/details/129589923