扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java鎬庝箞瀹炵幇鏂囦欢涓嬭浇鍔熻兘

扬州沐宇科技
2024-04-08 09:56:39
Java

鍦↗ava涓彲浠ラ€氳繃浣跨敤URLConnection绫绘潵瀹炵幇鏂囦欢涓嬭浇鍔熻兘銆備互涓嬫槸涓€涓畝鍗曠殑绀轰緥浠g爜锛?/p>

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

鍦ㄨ繖涓ず渚嬩腑锛屾垜浠鍏堝垱寤轰竴涓猆RL瀵硅薄锛岀劧鍚庨€氳繃璋冪敤openConnection()鏂规硶鑾峰彇URLConnection瀵硅薄銆傛帴鐫€鎴戜滑鑾峰彇杈撳叆娴佸苟灏嗗叾鍐欏叆鍒颁竴涓枃浠惰緭鍑烘祦涓紝鏈€鍚庡叧闂緭鍏ヨ緭鍑烘祦銆傝繖鏍峰氨瀹炵幇浜嗘枃浠朵笅杞藉姛鑳姐€?/p>

扫码添加客服微信