Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

public class Main {
    public static byte[] downloadImageFromURL(String strUrl) throws Exception {
        InputStream in;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        URL url = new URL(strUrl);
        in = new BufferedInputStream(url.openStream());
        byte[] buf = new byte[2048];
        int n = 0;
        while (-1 != (n = in.read(buf))) {
            out.write(buf, 0, n);
        }
        out.close();
        in.close();
        byte[] response = out.toByteArray();
        FileOutputStream fos = new FileOutputStream("/Users/image.jpg");
        fos.write(response);
        fos.close();
        return response;
    }

    public static void main(String[] args) throws Exception {
        downloadImageFromURL("http://www.java2s.com/style/download.png");

    }
}