package org.jeecg.common.util; import org.jeecg.common.util.encryption.AesEncryptUtil; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class LoadFileUtil { public static void main(String[] args) { try { // downLoadFromUrl("", ""); delFile("D:\\tets1\\app\\TEST视频-1565073368755.mp4"); } catch (Exception e) { e.printStackTrace(); } } /** * 上传文件 * * @param urlStr * @param savePath * @return * @throws IOException */ public static String downLoadFromUrl(String urlStr, String savePath) throws IOException { String fileName = AesEncryptUtil.getURLDecoderString(urlStr.substring(urlStr.lastIndexOf("/") + 1)); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(60 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //得到输入流 InputStream inputStream = conn.getInputStream(); //获取自己数组 byte[] getData = readInputStream(inputStream); //文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } String localPath = saveDir + File.separator + fileName; File file = new File(localPath); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } return localPath; } public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } /** * 删除文件 * * @param path * @return */ public static boolean delFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } try { flag = file.delete(); } catch (Exception e) { e.printStackTrace(); } return flag; } }