To get a file from a URL to save to a local code

Source: Internet
Author: User
Tags count return string stringbuffer
Often used, first put here, use the time to come and take! < % @pageImport= "Java.net.*,java.io.*"%>
<%!
public boolean Saveurlas (String Photourl, String fileName) {//This method can only be user HTTP protocol
try {
URL url = new URL (photourl);
HttpURLConnection connection = (httpurlconnection) url.openconnection ();
DataInputStream in = new DataInputStream (Connection.getinputstream ());
DataOutputStream out = new DataOutputStream (new FileOutputStream (FileName));
byte[] buffer = new byte[4096];
int count = 0;
while ((count = in.read (buffer)) > 0) {
Out.write (buffer, 0, count);
}
Out.close ();
In.close ();
return true;
}
catch (Exception e) {
return false;
}
public string Getdocumentat (String urlstring) {//This method is compatible with HTTP and FTP protocols
StringBuffer document = new StringBuffer ();
try {
URL url = new URL (urlstring);
URLConnection conn = Url.openconnection ();
BufferedReader reader = new BufferedReader (new InputStreamReader (conn).
getInputStream ()));
String line = null;
while (line = Reader.readline ())!= null) {
Document.append (line + "\ n");
}
Reader.close ();
}
catch (Malformedurlexception e) {
System.out.println ("Unable to connect to URL:" + urlstring);
}
catch (IOException e) {
System.out.println ("IOException when connecting to URL:" + urlstring);
}
return document.tostring ();
}
%>
<%
Test
String Photourl = " http://www.alixixi.com/UploadPic/2007-7/200777112920214.jpg";
String fileName = photourl.substring (Photourl.lastindexof ("/"));
String FilePath = "d:/ghost/";
Boolean flag = Saveurlas (Photourl, FilePath + fileName);
Out.println ("Run ok!\n<br>get URL file" + flag);
%>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.