溫馨提示×

java下載文件時如何處理異常

小樊
144
2024-07-02 19:04:16
欄目: 編程語言

在Java中下載文件時,需要處理可能出現的異常,以確保程序能夠正常運行。以下是處理異常的一種常見方法:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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 saveFilePath = "file.txt";

        try {
            URL url = new URL(fileUrl);
            URLConnection connection = url.openConnection();
            BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
            FileOutputStream out = new FileOutputStream(saveFilePath);

            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();
            System.out.println("Error downloading file: " + e.getMessage());
        }
    }
}

在上面的示例中,我們使用了try-catch語句捕獲可能發生的IOException異常。如果下載文件時出現異常,將打印異常信息并顯示錯誤消息。您還可以根據具體的需求來處理不同的異常情況。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女