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();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值