1. 程式人生 > >java從網路中下載圖片到本地

java從網路中下載圖片到本地

public class imageDownload {
    public static void main(String[] args) {

        String url = "http://localhost:8080/image/touxiang.png";

         String imageName =  "F:/test.jpg";

        downloadPicture(url,imageName);
    }
    //連結url下載圖片
    private static void downloadPicture(String urlList,String imageName) {
        URL url = null;
        int imageNumber = 0;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context=output.toByteArray();
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}