import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import model.SongXMLModel;
public class DownloadThread implements Runnable {
public SongXMLModel songXMLModel;
private long FileLength;// 文件总长度
private long DownedFileLength = 0;
private InputStream inputStream;
private HttpURLConnection connection;
private OutputStream outputStream;
private String mp3Path = "D:\\music_server/mp3";// MP3文件存放位置
private String lrcPath = "D:\\music_server/lrc";// lrc文件下载位置
private String lrcLink = "http://box.zhangmen.baidu.com/bdlrc/";
public DownloadThread(SongXMLModel songXMLModel) {
// TODO Auto-generated constructor stub
this.songXMLModel = songXMLModel;
}
@Override
public void run() {
// TODO Auto-generated method stub
downFile(mp3URL, mp3Path, ".mp3");
}
/*根据获得的URL地址下载文件*/
private void downFile(String urlString, String path, String type) {
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
if (connection.getReadTimeout() == 5) {
System.out.println("---------->当前网络有问题");
// return;
}
InputStream inputStream = connection.getInputStream();
String savePath = mp3Path + "/" + songXMLModel.getSongName()
+ ".mp3";
int bufferSize = 8192;
byte[] buf = new byte[bufferSize];
int passedlen = 0;
long len = 0;
DataOutputStream fileOut = new DataOutputStream(
new BufferedOutputStream(new BufferedOutputStream(
new FileOutputStream(savePath))));
System.out.println("文件的长度为:" + len + "\n");
System.out.println("开始接收文件!" + "\n");
while (true) {
int read = 0;
if (inputStream != null) {
read = inputStream.read(buf);
}
passedlen += read;
if (read == -1) {
break;
}
// 下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比
//System.out.println("文件接收了" + (passedlen));
fileOut.write(buf, 0, read);
}
System.out.println("接收完成,文件存为" + savePath + "\n");
fileOut.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
通过URL连接下载网络资源(基本)
最新推荐文章于 2023-04-04 12:01:42 发布