| | |
| | | */ |
| | | public static File downloadFile(String fileUrl) { |
| | | File downloadedFile = null; |
| | | |
| | | try { |
| | | URL url = new URL(fileUrl); |
| | | HttpURLConnection connection = (HttpURLConnection) url.openConnection(); |
| | | connection.setRequestMethod("GET"); |
| | | downloadedFile = new File(File.createTempFile("temp", ".jpeg").toURI()); |
| | | InputStream inputStream = connection.getInputStream(); |
| | | OutputStream outputStream = new FileOutputStream(downloadedFile); |
| | | byte[] buffer = new byte[1024]; |
| | | int bytesRead; |
| | | while ((bytesRead = inputStream.read(buffer)) != -1) { |
| | | outputStream.write(buffer, 0, bytesRead); |
| | | |
| | | // 创建临时文件 |
| | | File tempFile = File.createTempFile("temp", ".jpeg"); |
| | | downloadedFile = tempFile; |
| | | |
| | | // 使用 try-with-resources 确保流被关闭 |
| | | try (InputStream inputStream = connection.getInputStream(); |
| | | OutputStream outputStream = new FileOutputStream(downloadedFile)) { |
| | | byte[] buffer = new byte[1024]; |
| | | int bytesRead; |
| | | while ((bytesRead = inputStream.read(buffer)) != -1) { |
| | | outputStream.write(buffer, 0, bytesRead); |
| | | } |
| | | } |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |