LoadFileUtil.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package org.jeecg.common.util;
  2. import org.jeecg.common.util.encryption.AesEncryptUtil;
  3. import java.io.*;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. public class LoadFileUtil {
  7. public static void main(String[] args) {
  8. try {
  9. // downLoadFromUrl("", "");
  10. delFile("D:\\tets1\\app\\TEST视频-1565073368755.mp4");
  11. } catch (Exception e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. /**
  16. * 上传文件
  17. *
  18. * @param urlStr
  19. * @param savePath
  20. * @return
  21. * @throws IOException
  22. */
  23. public static String downLoadFromUrl(String urlStr, String savePath) throws IOException {
  24. String fileName = AesEncryptUtil.getURLDecoderString(urlStr.substring(urlStr.lastIndexOf("/") + 1));
  25. URL url = new URL(urlStr);
  26. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  27. //设置超时间为3秒
  28. conn.setConnectTimeout(60 * 1000);
  29. //防止屏蔽程序抓取而返回403错误
  30. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  31. //得到输入流
  32. InputStream inputStream = conn.getInputStream();
  33. //获取自己数组
  34. byte[] getData = readInputStream(inputStream);
  35. //文件保存位置
  36. File saveDir = new File(savePath);
  37. if (!saveDir.exists()) {
  38. saveDir.mkdir();
  39. }
  40. String localPath = saveDir + File.separator + fileName;
  41. File file = new File(localPath);
  42. FileOutputStream fos = new FileOutputStream(file);
  43. fos.write(getData);
  44. if (fos != null) {
  45. fos.close();
  46. }
  47. if (inputStream != null) {
  48. inputStream.close();
  49. }
  50. return localPath;
  51. }
  52. public static byte[] readInputStream(InputStream inputStream) throws IOException {
  53. byte[] buffer = new byte[1024];
  54. int len = 0;
  55. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  56. while ((len = inputStream.read(buffer)) != -1) {
  57. bos.write(buffer, 0, len);
  58. }
  59. bos.close();
  60. return bos.toByteArray();
  61. }
  62. /**
  63. * 删除文件
  64. *
  65. * @param path
  66. * @return
  67. */
  68. public static boolean delFile(String path) {
  69. boolean flag = false;
  70. File file = new File(path);
  71. if (!file.exists()) {
  72. return flag;
  73. }
  74. try {
  75. flag = file.delete();
  76. } catch (Exception e) {
  77. e.printStackTrace();
  78. }
  79. return flag;
  80. }
  81. }