IO流和URL实现下载文件

IO流和URL实现下载文件

  • 这里以下载微信安装包为例
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlTest {
    
    

    public static void main(String[] args) {
    
    

        //提升作用域
        HttpURLConnection connection = null;
        InputStream is = null;
        FileOutputStream fos = null;

        try {
    
    
            //url路径(微信安装包的URL)
            URL url = new URL
                    ("https://dl.softmgr.qq.com/original/im/WeChatSetup_3.1.0.72.exe");

            //获取到HttpURLConnction对象
            connection = (HttpURLConnection) url.openConnection();

            //通过连接对象获取到输入流
            is = connection.getInputStream();

            //文件保存位置
            fos = new FileOutputStream(new File("/file/微信PC.exe"));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
    
    

                fos.write(buffer, 0, len);

            }

            System.out.println("下载完毕");

        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //关闭资源
            try {
    
    
                fos.close();
                is.close();
                connection.disconnect();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }

    }

}

猜你喜欢

转载自blog.csdn.net/weixin_44412272/article/details/115356392
今日推荐