在Java中可以通過使用URLConnection類來實現文件下載功能。以下是一個簡單的示例代碼:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownload {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.zip";
String outputFilePath = "file.zip";
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(outputFilePath);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
在這個示例中,我們首先創建一個URL對象,然后通過調用openConnection()方法獲取URLConnection對象。接著我們獲取輸入流并將其寫入到一個文件輸出流中,最后關閉輸入輸出流。這樣就實現了文件下載功能。