LoadFileUtil.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3");
  27. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  28. //设置超时间为3秒
  29. conn.setConnectTimeout(60 * 1000);
  30. //防止屏蔽程序抓取而返回403错误
  31. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  32. //得到输入流
  33. InputStream inputStream = conn.getInputStream();
  34. //获取自己数组
  35. byte[] getData = readInputStream(inputStream);
  36. //文件保存位置
  37. File saveDir = new File(savePath);
  38. if (!saveDir.exists()) {
  39. saveDir.mkdir();
  40. }
  41. String localPath = saveDir + File.separator + fileName;
  42. File file = new File(localPath);
  43. FileOutputStream fos = new FileOutputStream(file);
  44. fos.write(getData);
  45. if (fos != null) {
  46. fos.close();
  47. }
  48. if (inputStream != null) {
  49. inputStream.close();
  50. }
  51. return localPath;
  52. }
  53. public static byte[] readInputStream(InputStream inputStream) throws IOException {
  54. byte[] buffer = new byte[1024];
  55. int len = 0;
  56. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  57. while ((len = inputStream.read(buffer)) != -1) {
  58. bos.write(buffer, 0, len);
  59. }
  60. bos.close();
  61. return bos.toByteArray();
  62. }
  63. /**
  64. * 删除文件
  65. *
  66. * @param path
  67. * @return
  68. */
  69. public static boolean delFile(String path) {
  70. boolean flag = false;
  71. File file = new File(path);
  72. if (!file.exists()) {
  73. return flag;
  74. }
  75. try {
  76. flag = file.delete();
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. }
  80. return flag;
  81. }
  82. }