java IO流从网页链接直接写入文件,无需本地转存
作者:互联网
写aspose word时有用到,网上的图片在磁盘转存会拖慢时间,就查了查,学了这种方法,可以整个在内存中操作。
操作图片示例
public void method() throws Exception {
//通过java.net.URL获取链接图片(java 1.8原生api)
//这里的链接不管是文件还是图片,
//一定是访问就直接下载或查看的那种,不能有其他内容
URL url = new URL("http://wenjuanba-pro.oss-cn-beijing.aliyuncs.com/null/image/2021/6/15/4287dd83cd4f474288aaa72c4d3de2ac.png");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//不用一直开启,如果获取失败可以尝试设置这几项
// httpURLConnection.setDoInput(true);
// httpURLConnection.setRequestMethod("GET");
// httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//获取图片长度,创建存放数据的byte数组
httpURLConnection.getContentLength();
byte[] result = new byte[httpURLConnection.getContentLength()];
//通过java.net.HttpURLConnection创建输入流(java 1.8原生api)
InputStream inputStream = httpURLConnection.getInputStream();
//通过read(byte[])来将数据存入创建好的数组,无需接受返回值
//这里就已经完成了
inputStream.read(result);
//aspose word api 用来输出word的
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
//将文件写入word里
builder.insertImage(result,125L,100L);
doc.save("src/main/resources/createSurveyWord/testImage/test.docx", SaveFormat.DOCX);//本地环境
inputStream.close();
}
标签:word,java,URL,流从,IO,new,byte,httpURLConnection 来源: https://blog.csdn.net/weixin_43971777/article/details/117981598