7 Sept 2012

Image downloading from web in java code


mport org.w3c.tidy.*;
import java.io.*;
import java.net.*;
import org.w3c.dom.*;
import java.util.*;
public class demo
{
public static void main(String arg[])
{
try
{
InputStream input = new URL("http://www.southreels.com").openStream();
Document document = new Tidy().parseDOM(input, null);
NodeList imgs = document.getElementsByTagName("img");
List<String> srcs = new ArrayList<String>();

for (int i = 0; i < imgs.getLength(); i++) {
    srcs.add(imgs.item(i).getAttributes().getNamedItem("src").getNodeValue());
}
int i=0;
for (String src: srcs) {
    System.out.println(i+"  "+src);
i++;
//}
String file =System.getProperty("user.dir")+System.getProperty("file.separator");
URL server = new URL(src);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
InputStream is = connection.getInputStream();
OutputStream os = new FileOutputStream(file+"demo"+i+".jpg");

    byte[] buffer = new byte[1024];
    int byteReaded = is.read(buffer);
    while(byteReaded != -1)
    {
        os.write(buffer,0,byteReaded);
byteReaded = is.read(buffer);
    }

   os.close();
}
}
catch(Exception e)
{
}
}
}

0 comments:

Post a Comment