java IO流从网页链接直接写入文件,无需本地转存

2021/6/17 12:30:02

本文主要是介绍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();
    }


这篇关于java IO流从网页链接直接写入文件,无需本地转存的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程