要在Java中實現下載文件并顯示下載進度條,可以使用Java的URLConnection類來下載文件并監聽下載進度。以下是一個簡單的示例代碼:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class FileDownloader {
public static void main(String[] args) {
String fileUrl = "http://example.com/file.txt";
String savePath = "file.txt";
try {
URL url = new URL(fileUrl);
URLConnection connection = url.openConnection();
int fileSize = connection.getContentLength();
InputStream inputStream = connection.getInputStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int bytesRead;
int totalBytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
int percentage = (int) ((totalBytesRead / (float) fileSize) * 100);
System.out.println("Downloaded " + percentage + "%");
}
inputStream.close();
outputStream.close();
System.out.println("File downloaded successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
在上面的代碼中,我們首先獲取文件的大小,然后創建一個輸入流來讀取文件內容,并創建一個輸出流來將文件內容寫入到本地文件。在讀取文件內容的過程中,我們計算已下載的文件大小占總文件大小的百分比,并將進度顯示在控制臺上。
請注意,這只是一個簡單的示例代碼,實際場景中可能需要更復雜的邏輯來處理異常、顯示進度條等。