Java

java下载文件如何实现进度条显示

小樊
235
2024-07-02 19:09:13
栏目: 编程语言

要在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();
        }
    }

}

在上面的代码中,我们首先获取文件的大小,然后创建一个输入流来读取文件内容,并创建一个输出流来将文件内容写入到本地文件。在读取文件内容的过程中,我们计算已下载的文件大小占总文件大小的百分比,并将进度显示在控制台上。

请注意,这只是一个简单的示例代码,实际场景中可能需要更复杂的逻辑来处理异常、显示进度条等。

0
看了该问题的人还看了