使用HttpURLConnection下载文件时经常会出现 java.io.FileNotFoundException文件找不到异常,下面介绍下解决办法

首先设置tomcat对get数据的编码:conf/server.xml

  1. <Connector port="8080" protocol="HTTP/1.1"
  2. connectionTimeout="20000"
  3. redirectPort="8443"
  4. <span style="color:#ff0000;"> URIEncoding="UTF-8"</span> />

其次对请求的文件名进行编码:

  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.RandomAccessFile;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. import java.net.URLEncoder;
  8. /**
  9. * 多线程下载
  10. * @author bing
  11. *
  12. */
  13. public class OmbDownloadOfThreadsUtil {
  14. private String urlPath ; // 资源网络路径
  15. private String targetFilePath ; // 所下载文件的保存路径
  16. private int threadNum ; // 启用多少条线程进行下载
  17. // 用于下载线程对象集合
  18. private DownloadThread[] downloadThreads ;
  19. // 要下载文件的大小
  20. private int fileSize ;
  21. public OmbDownloadOfThreadsUtil(String urlPath, String targetFilePath,
  22. int threadNum) {
  23. this.urlPath = urlPath;
  24. this.targetFilePath = targetFilePath;
  25. this.threadNum = threadNum;
  26. downloadThreads = new DownloadThread[threadNum] ;
  27. }
  28. public void downloadFile() throws Exception{
  29. URL url = new URL(urlPath) ;
  30. HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
  31. conn.setConnectTimeout(4*1000) ;
  32. conn.setRequestMethod("GET") ;
  33. conn.setRequestProperty(
  34. "Accept",
  35. "image/gif, image/jpeg, image/pjpeg, image/pjpeg, " +
  36. "application/x-shockwave-flash, application/xaml+xml, " +
  37. "application/vnd.ms-xpsdocument, application/x-ms-xbap, " +
  38. "application/x-ms-application, application/vnd.ms-excel, " +
  39. "application/vnd.ms-powerpoint, application/msword, */*");
  40. conn.setRequestProperty("Accept-Language", "zh-CN");
  41. conn.setRequestProperty("Charset", "UTF-8");
  42. //设置浏览器类型和版本、操作系统,使用语言等信息
  43. conn.setRequestProperty(
  44. "User-Agent",
  45. "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/4.0; " +
  46. ".NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; " +
  47. ".NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
  48. //设置为长连接
  49. conn.setRequestProperty("Connection", "Keep-Alive");
  50. //得到要下载文件的大小
  51. fileSize = conn.getContentLength() ;
  52. System.out.println("fileSize:"+fileSize);
  53. //断开连接
  54. conn.disconnect() ;
  55. //计算每条线程需要下载的大小
  56. int preThreadDownloadSize = fileSize/threadNum+1 ;
  57. System.out.println("preThreadDownloadSize:"+preThreadDownloadSize);
  58. RandomAccessFile file = new RandomAccessFile(targetFilePath, "rw") ;
  59. file.setLength(fileSize) ;
  60. file.close() ;
  61. for (int i = 0; i < threadNum; i++) {
  62. // 计算每条线程下载的起始位置
  63. int startPos = i*preThreadDownloadSize+1 ;
  64. RandomAccessFile currentPart = new RandomAccessFile(targetFilePath, "rw") ;
  65. currentPart.seek(startPos) ;
  66. downloadThreads[i] = new DownloadThread(startPos,preThreadDownloadSize,currentPart) ;
  67. new Thread(downloadThreads[i]).start() ;
  68. }
  69. }
  70. /**
  71. * 获取下载的完成百分比
  72. * @return 完成的百分比
  73. */
  74. public double getCompleteRate() {
  75. // 统计多条线程已经下载的总大小
  76. int sumSize = 0;
  77. for (int i = 0; i < threadNum; i++) {
  78. sumSize += downloadThreads[i].hasReadLength;
  79. }
  80. // 返回已经完成的百分比
  81. return sumSize * 1.0 / fileSize;
  82. }
  83. /**
  84. * 用于下载的线程
  85. * @author bing
  86. *
  87. */
  88. private final class DownloadThread implements Runnable{
  89. private int startPos ;
  90. private int preThreadDownloadSize ;
  91. private RandomAccessFile currentPart ;
  92. //已下载长度
  93. private int hasReadLength ;
  94. public DownloadThread(int startPos, int preThreadDownloadSize,
  95. RandomAccessFile currentPart) {
  96. this.startPos = startPos;
  97. this.preThreadDownloadSize = preThreadDownloadSize;
  98. this.currentPart = currentPart;
  99. }
  100. @Override
  101. public void run() {
  102. InputStream inputStream = null ;
  103. try{
  104. URL url = new URL(urlPath) ;
  105. HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
  106. conn.setConnectTimeout(4*1000) ;
  107. conn.setRequestMethod("GET") ;
  108. conn.setRequestProperty(
  109. "Accept",
  110. "image/gif, image/jpeg, image/pjpeg, image/pjpeg, " +
  111. "application/x-shockwave-flash, application/xaml+xml, " +
  112. "application/vnd.ms-xpsdocument, application/x-ms-xbap, " +
  113. "application/x-ms-application, application/vnd.ms-excel, " +
  114. "application/vnd.ms-powerpoint, application/msword, */*");
  115. conn.setRequestProperty("Accept-Language", "zh-CN");
  116. conn.setRequestProperty("Charset", "UTF-8");
  117. inputStream = conn.getInputStream() ;
  118. inputStream.skip(startPos) ;//定位到开始位置
  119. byte[] buffer = new byte[1024] ;
  120. int temp = 0 ;
  121. while(hasReadLength<preThreadDownloadSize
  122. &&(temp=inputStream.read(buffer))!=-1){
  123. currentPart.write(buffer,0,temp) ;
  124. hasReadLength += temp ;
  125. }
  126. }catch(Exception e){
  127. e.printStackTrace() ;
  128. }finally{
  129. try {
  130. currentPart.close() ;
  131. } catch (Exception e) {
  132. e.printStackTrace();
  133. }
  134. try {
  135. inputStream.close() ;
  136. } catch (Exception e) {
  137. e.printStackTrace();
  138. }
  139. }
  140. }
  141. }
  142. public static void main(String[] args) throws Exception {
  143. String songName = "许嵩 - 半城烟沙.mp3" ;
  144. songName = URLEncoder.encode(songName,"UTF-8") ;
  145. String urlPath = "http://172.16.2.50:8080/mp3/"+songName ;
  146. String targetDir = "E:"+File.separator+songName ;
  147. OmbDownloadOfThreadsUtil odtu = new OmbDownloadOfThreadsUtil(urlPath,targetDir, 6) ;
  148. odtu.downloadFile() ;
  149. }
  150. }

经过以上三步基本上问题已经解决,但如果的文件名含有空格的话还需一步:

URLs是不能包含空格的。URL encoding一般会使用“+”号去替换空格,但后台服务器(我的是Tomcat6.0)又不能把“+”还原为空格,所以导致文件找不到,解决办法:只需把“+”替换为“%20”

    1. public static void main(String[] args) throws Exception {
    2. String songName = "许嵩 - 半城烟沙.mp3" ;
    3. songName = URLEncoder.encode(songName,"UTF-8").replace("+", "%20") ;
    4. String urlPath = "http://172.16.2.50:8080/mp3/"+songName ;
    5. String targetDir = "E:"+File.separator+songName ;
    6. OmbDownloadOfThreadsUtil odtu = new OmbDownloadOfThreadsUtil(urlPath,targetDir, 6) ;
    7. odtu.downloadFile() ;
    8. }

使用HttpURLConnection下载文件时出现 java.io.FileNotFoundException彻底解决办法的更多相关文章

  1. MS SQL执行大脚本文件时,提示“内存不足”的解决办法()

    问题描述: 当客户服务器不允许直接备份时,往往通过导出数据库脚本的方式来部署-还原数据库, 但是当数据库导出脚本很大,用Microsoft SQL Server Management Studio执行 ...

  2. MS SQL2008执行大脚本文件时,提示“内存不足”的解决办法

    问题描述: 当客户服务器不允许直接备份时,往往通过导出数据库脚本的方式来部署-还原数据库, 但是当数据库导出脚本很大,用Microsoft SQL Server Management Studio执行 ...

  3. MSSQL执行大脚本文件时,提示“内存不足”的解决办法

    导出了一个脚本文件,将近900M,回来往sql studio一丢,报了个内存不足,然后就有了此文.. 问题描述: 当客户服务器不允许直接备份时,往往通过导出数据库脚本的方式来部署-还原数据库, 但是当 ...

  4. SQL SERVER 2008R2 执行大脚本文件时,提示“内存不足”的解决办法

    我把一个数据库的架构及数据都已脚本的方式拷贝下来,再去新建一个数据库想把脚本执行一下,但提示如下错误: 问题描述: 当客户服务器不允许直接备份时,往往通过导出数据库脚本的方式来部署-还原数据库, 但是 ...

  5. 使用Android SDK Manager下载sdk时总是出现中断异常的解决办法。

    1.搜到到你本机的hosts文件. 2.打开该文件. 3.在该文件最后一行添加:74.125.31.136 dl-ssl.google.com 4.重新下载问题解决. 参考链接:http://bbs. ...

  6. 关于在工程中添加新文件时的LNK2019错误的一个解决办法

    我这几天一直在研究Qt的串口程序,在读懂了官方给出的实例程序后我决定把其多线程的串口监视程序加入到我自己的工程中,便直接把问价复制到自己的工程下面,在Qt中加入到自己的工程中,但是总是出现LNK201 ...

  7. flask上传文件时request.files为空的解决办法

    在做上传文件的时候遇到request.files是空 原因在于html中的表单form没有指明 enctype="multipart/form-data" <form met ...

  8. GraphicsMagick java.io.FileNotFoundException: gm 错误解决办法

    GraphicsMagick java.io.FileNotFoundException: gm 解决办法, 方法一: ProcessStarter.setGlobalSearchPath(" ...

  9. Android下载文件提示文件不存在。。。 java.io.FileNotFoundException

    遇到这个错误java.io.FileNotFoundException,事实上文件是存在的,把地址复制到手机浏览器都能够直接下载的,但为嘛不能下载呢. Error in downloadBitmap ...

随机推荐

  1. UVA 291 The House Of Santa Claus (DFS求一笔画)

    题意:从左下方1开始,一笔画出圣诞老人的屋子(不过话说,圣诞老人的屋子是这样的吗?这算是个屋子么),输出所有可以的路径. 思路:贴代码. #include <iostream> #incl ...

  2. UVA 10523 Very Easy!!!(大数据加法、乘法)

    题意:给出N,A,计算i*A^i(i=1~N)的和.1<=N<=30,0<=A<=15. 就是大数据运算,别的没什么,注意细节之处即可. 这题还要注意两个地方: 1.考虑A=0 ...

  3. POJ2299Ultra-QuickSort

    http://poj.org/problem?id=2299 题意 : 排序,求排序次数,本来以为用冒泡可以搞定,事实上,那么大的数据以及一个TLE告诉我,会超时......... 思路 : 问了一下 ...

  4. lintcode: 二叉树的锯齿形层次遍历

    题目 二叉树的锯齿形层次遍历 给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行) 样例 给出一棵二叉树 {3,9,20,#,#,15,7}, 3 / \ ...

  5. lintcode 中等题:permutations 全排列

    题目 全排列 给定一个数字列表,返回其所有可能的排列. 您在真实的面试中是否遇到过这个题? Yes 样例 给出一个列表[1,2,3],其全排列为: [ [1,2,3], [1,3,2], [2,1,3 ...

  6. python流程控制语句 ifelse - 1

    考点:条件判断语句if-elif 代码: #! /usr/bin/python print ('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n') p ...

  7. Django admin site(二)ModelAdmin methods

    ModelAdmin methods save_model(request, obj, form, change) 此方法为admin界面用户保存model实例时的行为.request为HttpReq ...

  8. BZOJ 1923 外星千足虫(高斯消元)

    题目链接:http://61.187.179.132/JudgeOnline/problem.php?id=1923 题意:有n个数字,m次测试.每个数字为0或者1.每次测试选出一些数字出来把他们加起 ...

  9. windows线程同步

    一.前言 之前在项目中,由于需要使用到多线程,多线程能够提高执行的效率,同时也带来线程同步的问题,故特此总结如下. 二.windows线程同步机制 windows线程同步机制常用的有几种:Event. ...

  10. 使用截图方式将Excel导出为PNG图片的不可行性

    博主前面一篇文章使用了JAVA的Robot机制 模拟打开Excel然后Robot移动到指定区域,截图并生成PNG格式图片 试图使用这种方式将复杂的Excel报表转化成无差别的PNG图片 但是这种方式遇 ...