可以使用Java的URLConnection類來實現文件下載功能。下面是一個簡單的示例代碼:
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class FileDownload {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String savePath = "downloaded_file.txt";
try {
URL url = new URL(fileUrl);
URLConnection conn = url.openConnection();
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
FileOutputStream out = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.close();
in.close();
System.out.println("File downloaded successfully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
在這個示例中,我們首先創建一個URL對象,然后通過URLConnection打開連接并獲取輸入流。接著創建一個輸出流,并使用循環來讀取輸入流中的數據并寫入輸出流中,直到讀取完整個文件。最后關閉輸出流和輸入流,并輸出下載成功的提示。