Java. Io. filenotfoundexception occurs when files are downloaded using httpurlconnection.

Source: Internet
Author: User

Java. Io. filenotfoundexception file cannot be found when you use httpurlconnection to download files. The following describes the solution.

First, set the Tomcat code for get data: CONF/server. xml

    <Connector port="8080" protocol="HTTP/1.1"                connectionTimeout="20000"                redirectPort="8443"   URIEncoding="UTF-8" />

Encode the requested file name:

Import Java. io. file; import Java. io. ioexception; import Java. io. inputstream; import Java. io. randomaccessfile; import java.net. httpurlconnection; import java.net. URL; import java.net. urlencoder;/*** multi-thread download * @ author Bing **/public class ombdownloadofthreadsutil {private string urlpath; // resource network path private string targetfilepath; // The storage path of the downloaded file is private int threadnum; // how many threads are enabled for download // used to download the thread object set Private downlo Adthread [] downloadthreads; // Private int filesize of the file to be downloaded; Public ombdownloadofthreadsutil (string urlpath, string targetfilepath, int threadnum) {This. urlpath = urlpath+this.tar getfilepath = targetfilepath; this. threadnum = threadnum; downloadthreads = new downloadthread [threadnum];} public void downloadfile () throws exception {URL url = new URL (urlpath); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (4*1000); Conn. setrequestmethod ("get"); Conn. setrequestproperty ("accept", "image/GIF, image/JPEG, image/pjpeg, image/pjpeg," + "application/X-Shockwave-flash, application/XAML + XML, "+" application/vnd. MS-xpsdocument, application/X-MS-xbap, "+" application/X-MS-application, application/vnd. MS-Excel, "+" application/vnd. MS-PowerPoint, application/MSWord ,* /* "); Conn. setrequestproperty ("Accept-language", "ZH-CN"); Conn. setrequestproperty ("charset", "UTF-8"); // sets the browser type and version, operating system, language and other information Conn. setrequestproperty ("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0;" + ". net CLR 1.1.4322 ;. net CLR 2.0.50727 ;. net CLR 3.0.04506.30; "+ ". net CLR 3.0.20.6.2152 ;. net CLR 3.5.30729) "); // set to persistent connection Conn. setrequestproperty ("connection", "Keep-aliv E "); // obtain the file size to be downloaded. filesize = Conn. getcontentlength (); system. out. println ("filesize:" + filesize); // disconnect Conn. disconnect (); // calculate the size of each thread to be downloaded. Int prethreaddownloadsize = filesize/threadnum + 1; system. out. println ("prethreaddownloadsize:" + prethreaddownloadsize); randomaccessfile file = new randomaccessfile (targetfilepath, "RW"); file. setlength (filesize); file. close (); For (INT I = 0; I <threadnum; I ++) {// Calculation Start position of each thread download: int startpos = I * prethreaddownloadsize + 1; randomaccessfile currentpart = new randomaccessfile (targetfilepath, "RW"); currentpart. seek (startpos); downloadthreads [I] = new downloadthread (startpos, prethreaddownloadsize, currentpart); New thread (downloadthreads [I]). start () ;}}/*** get download completion percentage * @ return completion percentage */Public double getcompleterate () {// count the total size int sumsize = 0; For (INT I = 0; I <threadnum; I ++) {sumsize + = downloadthreads [I]. hasreadlength;} // return the percentage of completed results. Return sumsize * 1.0/filesize ;} /*** download thread * @ author Bing **/private final class downloadthread implements runnable {private int startpos; private int prethreaddownloadsize; private randomaccessfile currentpart; // download length: Private int hasreadlength; Public downloadthread (INT startpos, int prethreaddownloadsize, randomac Cessfile currentpart) {This. startpos = startpos; this. prethreaddownloadsize = prethreaddownloadsize; this. currentpart = currentpart;} @ overridepublic void run () {inputstream = NULL; try {URL url = new URL (urlpath); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (4*1000); Conn. setrequestmethod ("get"); Conn. setrequestproperty ("accept", "image/GIF, IMA Ge/JPEG, image/pjpeg, image/pjpeg, "+" application/X-Shockwave-flash, application/XAML + XML, "+" application/vnd. MS-xpsdocument, application/X-MS-xbap, "+" application/X-MS-application, application/vnd. MS-Excel, "+" application/vnd. MS-PowerPoint, application/MSWord, */* "); Conn. setrequestproperty ("Accept-language", "ZH-CN"); Conn. setrequestproperty ("charset", "UTF-8"); inputstream = Conn. getinputstrea M (); inputstream. skip (startpos); // locate the start position byte [] buffer = new byte [1024]; int temp = 0; while (hasreadlength <prethreaddownloadsize & (temp = inputstream. read (buffer ))! =-1) {currentpart. write (buffer, 0, temp); hasreadlength + = temp ;}} catch (exception e) {e. printstacktrace ();} finally {try {currentpart. close ();} catch (exception e) {e. printstacktrace ();} Try {inputstream. close ();} catch (exception e) {e. printstacktrace () ;}}} public static void main (string [] ARGs) throws exception {string songname = "Xu wei-bu chengsha"; songname = urlencoder. encode (songname, "UTF-8"); string urlpath = "http: // 172.16.2.50: 8080/MP3/" + songname; string targetdir = "E:" + file. separator + songname; ombdownloadofthreadsutil odtu = new ombdownloadofthreadsutil (urlpath, targetdir, 6); odtu. downloadfile ();}}

After the above three steps, the problem has been solved, but if the file name contains spaces, you still need:

URLs cannot contain spaces. Generally, URL encoding uses the "+" sign to replace spaces. However, the backend server (My tomcat6.0) cannot restore "+" to spaces, so the file cannot be found, solution: Replace "+" with "% 20"

Public static void main (string [] ARGs) throws exception {string songname = "Xu xiao-bancheng"; songname = urlencoder. encode (songname, "UTF-8 "). replace ("+", "% 20"); string urlpath = "http: // 172.16.2.50: 8080/MP3/" + songname; string targetdir = "E:" + file. separator + songname; ombdownloadofthreadsutil odtu = new ombdownloadofthreadsutil (urlpath, targetdir, 6); odtu. downloadfile ();}

 

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.