如何用java安全高效地下载文件

avatar
作者
筋斗云
阅读量:0

在Java中,可以使用java.net包中的URLConnection类来下载文件。以下是一个安全高效地下载文件的示例代码:

import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection;  public class FileDownloader {      public static void main(String[] args) {         String fileUrl = "https://example.com/file.txt";         String destinationPath = "downloaded_file.txt";          try {             URL url = new URL(fileUrl);             URLConnection urlConnection = url.openConnection();             InputStream inputStream = urlConnection.getInputStream();             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);             FileOutputStream fileOutputStream = new FileOutputStream(destinationPath);              byte[] buffer = new byte[4096];             int bytesRead;             while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {                 fileOutputStream.write(buffer, 0, bytesRead);             }              fileOutputStream.close();             bufferedInputStream.close();             inputStream.close();             System.out.println("File downloaded successfully.");         } catch (IOException e) {             e.printStackTrace();         }     } } 

在上面的代码中,我们首先创建一个URL对象,并使用它来打开一个URLConnection连接。然后,我们从连接中获取输入流,并使用缓冲输入流来提高性能。最后,我们将文件内容写入到目标文件中。

请注意,这只是一个简单的文件下载示例,并且没有考虑到一些安全和性能方面的问题。如果需要更高级的下载功能,建议使用Apache HttpClient或其他第三方库来处理文件下载。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!