Mega Code Archive

 
Categories / Java / Network Protocol
 

A URL Retrieval Example

import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; public class GetURL {   public static void main(String args[]) throws Exception {     URL url = new URL("http://www.google.com");     InputStream urlstream = url.openStream();     byte[] buffer = new byte[0];     byte[] chunk = new byte[4096];     int count;     while ((count = urlstream.read(chunk)) >= 0) {       byte[] t = new byte[buffer.length + count];       System.arraycopy(buffer, 0, t, 0, buffer.length);       System.arraycopy(chunk, 0, t, buffer.length, count);       buffer = t;     }     String filename = (url.getFile()).replace('/', File.separatorChar);     File f1 = new File(filename);     filename = f1.getName();     FileOutputStream f = null;     f = new FileOutputStream(filename);     f.write(buffer);     f.close();   } }