Skip to content

Instantly share code, notes, and snippets.

@prongbang
Created March 19, 2014 08:26
Show Gist options
  • Save prongbang/9637566 to your computer and use it in GitHub Desktop.
Save prongbang/9637566 to your computer and use it in GitHub Desktop.
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GetImg
{
public static void main(String[]args)
{
GetImg gi = new GetImg();
Scanner scan = new Scanner(System.in);
System.out.print("URL : ");
String url ="";
url = scan.nextLine();
System.out.println("Waitting. . .");
String html = gi.getContent(url); // get content web page
List<String> list = gi.getUrlImage(html); // get url image
System.out.println("Url " + list.size()); // size List
for(int i = 0; i < list.size(); i++)
System.out.println(list.get(i)); // get value of List
try{
//gi.download(url,"img.jpg");
System.out.print("Download Success!! \n");
}catch(Exception e){ System.out.print("Download Fail !! \n");}
} // main
public List<String> getUrlImage(String html){
List<String> list = new ArrayList<String>();
Pattern pat = null;
Matcher mat = null;
String word0 = null;
String word1 = null;
// .*<img[^>]*src=\"([^\"]*)
pat = Pattern.compile(".*<img[^>]*src=[\"']([^\"^']*)",Pattern.CASE_INSENSITIVE);
mat = pat.matcher(html);
while(mat.find())
{
word0 = mat.group(1);
list.add(word0.toString()); // add in List
}
return list;
}
public String getContent(String fromURL){
StringBuilder sb = new StringBuilder();
try {
URL url = new URL(fromURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
return sb.toString();
} catch (MalformedURLException e) { } catch (IOException e) { }
return "";
}
public void download(String fileURL, String fileOutPutPath) throws MalformedURLException {
try {
URL url = new URL(fileURL);
url.openConnection();
InputStream reader = url.openStream();
FileOutputStream writer = new FileOutputStream(fileOutPutPath);
byte[] buffer = new byte[153600];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
buffer = new byte[153600];
}
writer.close();
reader.close();
} catch (MalformedURLException e) { } catch (IOException e) { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment