Java下载图片一. 通过字节流传输

Java下载图片

 /*生成图片方法*/
    public void makeImg(String url,String directory) {
        try {
            //创建流
            BufferedInputStream bis = new BufferedInputStream(new URL(url).openStream());
            //生成图片名
            int index = url.lastIndexOf("/");
            String name = url.substring(index+1,url.length());
            System.out.println(name);
            //存放地址
            File img = new File(directory + name);
            //生成图片
            BufferedOutputStream bus = new BufferedOutputStream(new FileOutputStream(img));
            byte[] buf = new byte[2048];
            int length = bis.read(buf);
            while (length != -1) {
                bus.write(buf, 0, length);
                length = bis.read(buf);
            }
            bis.close();
            bus.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

你可能感兴趣的:(java,image,download)