1. 程式人生 > >連結url下載圖片

連結url下載圖片

public static void downloadPicture(List<String> urlList) {
        URL url = null;
        int j;
        List<String> urls = new ArrayList<>();
        for(int t=0;t<urlList.size();t++){
            if(!"".equals(urlList.get(t)) && urlList.get(t) != null){
                urls.add(urlList.get(t));
            }
        }
        if(urls.size() > 9){
            j = 9;
        }else{
            j = urls.size();
        }
        try {
            for(int i=0;i<j;i++){
                String path = "file"+i+".jpg";
                url = new URL(urlList.get(i));
                DataInputStream dataInputStream = new DataInputStream(url.openStream());
                FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = dataInputStream.read(buffer)) > 0) {
                    output.write(buffer, 0, length);
                }
                fileOutputStream.write(output.toByteArray());
                dataInputStream.close();
                fileOutputStream.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }