java从URL下载文件、图片到本地

傷城~ 2023-02-19 06:27 116阅读 0赞

有时候我们需要从网络上下载一个文件、图片、视频等到本地,不想依赖jar,就需要自己实现

代码:

  1. import java.io.*;
  2. import java.net.URL;
  3. import java.net.URLConnection;
  4. /**
  5. * @author : Vick C
  6. * @version : v1.0
  7. * @date : 2020/6/19
  8. */
  9. public class FileUtil {
  10. /**
  11. * download file from internet
  12. * @param fileUrl file url
  13. * @param fileName file name
  14. * @param savePath save path
  15. * @return success return the file path, fail return null
  16. */
  17. public static String downLoadFromInternet(String fileUrl, String fileName, String savePath) {
  18. try {
  19. URLConnection conn = new URL(fileUrl).openConnection();
  20. // 设置超时间为10秒
  21. conn.setConnectTimeout(10 * 1000);
  22. // 防止屏蔽程序抓取而返回403错误
  23. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  24. // 得到输入流
  25. InputStream inputStream = conn.getInputStream();
  26. // 获取字节数组
  27. byte[] byteArray = readInputStream(inputStream);
  28. assert byteArray != null;
  29. // 文件保存位置
  30. File saveDir = new File(savePath);
  31. if (!saveDir.exists()) {
  32. saveDir.mkdir();
  33. }
  34. File file = new File(saveDir + File.separator + fileName);
  35. FileOutputStream fos = new FileOutputStream(file);
  36. fos.write(byteArray);
  37. fos.close();
  38. inputStream.close();
  39. return saveDir + File.separator + fileName;
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43. return null;
  44. }
  45. /**
  46. * 从输入流中获取字节数组
  47. * @param inputStream input stream
  48. * @return byte array
  49. */
  50. public static byte[] readInputStream(InputStream inputStream) {
  51. try {
  52. byte[] buffer = new byte[1024];
  53. int len = 0;
  54. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  55. while ((len = inputStream.read(buffer)) != -1) {
  56. bos.write(buffer, 0, len);
  57. }
  58. bos.close();
  59. return bos.toByteArray();
  60. } catch (IOException e) {
  61. e.printStackTrace();
  62. }
  63. return null;
  64. }
  65. }

发表评论

表情:
评论列表 (有 0 条评论,116人围观)

还没有评论,来说两句吧...

相关阅读