19、java根据URL下载文件内容

本文介绍了一种简单的从URL下载文件的方法,包括使用普通流和NIO方式实现。通过创建URL对象并打开其流数据,然后保存到本地文件中,实现了文件的下载过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


package com.tij.io.file;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

/**
* 从URL下载文件,简单实例
* @author GYJ
* @date 2014-3-22
*/
public class DownloadFileFromURL {

/**
* 其实简单的流程就是打开URL的流数据,保存到我们本地文件
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//下载的地址
String url = "http://www.baidu.com/";
downloadUsingStream(url, "/Users/GYJ/java1.txt");
downloadUsingNIO(url, "/Users/GYJ/java1.txt");
}

/**
* 使用普通流的方式
* @param url 要下载的URL
* @param fileName 保存内容的文件
* @throws IOException
*/
private static void downloadUsingStream(String urlS, String fileName) throws IOException {
URL url = new URL(urlS);
BufferedInputStream bis = new BufferedInputStream(url.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
byte[] buffer = new byte[1024];
int count = 0;
while ((count = bis.read(buffer, 0, 1024)) != -1) {
fos.write(buffer, 0, count);
}
fos.close();
bis.close();
}

/**
* 使用NIO的方式
* @param urlS 要下载的URL
* @param fileName 保存内容的文件
* @throws IOException
*/
private static void downloadUsingNIO(String urlS, String fileName) throws IOException {
URL url = new URL(urlS);
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}

}



//====================下载结果===================
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel="dns-prefetch" href="//t12.baidu.com"/><title>百度一下,你就知道</title><style index="index" >html,body{height:100%}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center}#ftCon{height:100px;position:absolute;bottom:44px;text-align:center;width:100%;margin:0 auto;z-index:0;overflow:hidden}#ftConw{width:720px;margin:0 auto}body{font:12px arial;text-align:;background:#fff}body,p,form,ul,li{margin:0;padding:0;list-style:none}body,form,#fm{position:relative}td..........省略
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值