Java 利用url下载MP3保存到本地

这个Java程序展示了如何从URL下载MP3文件并保存到本地。它使用HttpURLConnection打开连接,通过BufferedInputStream读取网络流,并用FileOutputStream写入文件。程序创建线程执行下载任务,确保文件成功下载并输出相关信息。
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLFileSaver implements Runnable {

private static final int BUFFER_SIZE = 4096;
private String destUrl;
private String fileName;

public URLFileSaver(String destUrl,String fileName)
{
this.destUrl = destUrl;
int i = destUrl.lastIndexOf("/");
this.fileName = fileName + destUrl.substring(i+1);
}

public void run() {
try {
saveToFile(destUrl,fileName);

System.out.println("文件:"+destUrl+"下载完成,保存为"+fileName);
} catch (IOException e) {
System.out.println("文件下载失败,信息:"+e.getMessage());
}
}

// 将网络文件保存为本地文件的方法
// @param destUrl
// @param fileName
// @throws IOException

public void saveToFile(String destUrl, String fileName) throws IOException {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpconn = null;
URL url = null;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;

// 建立链接
url = new URL(destUrl);
httpconn = (HttpURLConnection) url.openConnection();
// 连接指定的资源
httpconn.connect();
// 获取网络输入流
bis = new BufferedInputStream(httpconn.getInputStream());
// 建立文件
fos = new FileOutputStream(fileName);

System.out.println("正在获取链接[" + destUrl + "]的内容\n将其保存为文件[" + fileName
+ "]");

// 保存文件
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
fos.close();
bis.close();
httpconn.disconnect();
}

public static void main(String[] args) {
Thread th = new Thread(new URLFileSaver("http://218.30.106.195:8083/MDNew/MediaRTGBBFbcd578190/liyuehong/SHE_FM_SHE_Future/05.mp3","c:/"));
th.start();
}

}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值