Java reads Web page picture path and downloads to local
Recently the company needs to crawl some of the data on the Web page, and simply wrote a demo, some of which are pictures that need to be downloaded to the local and
Save the path of the picture to the database, the sample code is as follows:
Package com.cellstrain.icell.util;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import Java.net.URL;
Import java.net.URLConnection;
Import Java.util.Date;
public class Downloadimage {
/**
*@paramArgs
*@throwsException
*/
public static void Main (string[] args)Throws Exception {
Download"Https://www.mybiosource.com/images/tds/protocol_images/1000000-6999999/MBS2031060_SDS.jpg",E\\Upload\\Sdspage ");
}
public static string Download (String urlpath,string savepath)Throws Exception {
Construct URL
URL url =New URL (URLPath);
Open connection
URLConnection con = url.openconnection ();
Set request Timeout to 5s
Con.setconnecttimeout (5*1000);
Input stream
InputStream is = Con.getinputstream ();
1K of data buffering
Byte[] bs =New byte[1024];
Length of data read
int Len;
The output file stream
File sf=New File (Savepath);
if (!sf.exists ()) {
Sf.mkdirs ();
}
int randomno= (int) (Math.Random () *1000000);
String filename=urlpath.substring (Urlpath.lastindexof ("/")+1,urlpath.length ());Get the name of the server slice
Filename=New Java.text.SimpleDateFormat ("Yyyy-mm-dd-hh-mm-ss"). Format (New Date ()) +randomno+filename;Time + random number prevents duplication
OutputStream OS = new FileOutputStream (Sf.getpath () + "\\ "+filename);
String virtualpath= "/upload/sdspage/" +filename;//the virtual path to the database
//start reading
while (len = Is.read (BS))! =-1) {
Os.write (BS, 0, Len);
}
//complete, close all links
Os.close ();
Is.close ();
return virtualpath;
}
}
is tomcat to configure the virtual path Oh, if it is not clear how to configure the virtual path can be viewed http:// www.cnblogs.com/qianzf/p/6781143.html < Span style= "color: #808080; Font-style:italic ">
Java reads Web page picture path and downloads to local