从某网站下载MP3的例子

从某网站下载MP3的例子。为安全起见,将网站信息匿了。



package tools.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class DownloadMP3 {
private static final String SITE = ...
private static final String SAVE_PATH = ...
private static int BUFFER_SIZE = 1024 * 8;

public boolean downloadSrc(String strURL, String saveFile) {

// strURL validation ....

BufferedInputStream bis = null;
FileOutputStream fos = null;
byte[] buf = new byte[BUFFER_SIZE];

try {
File dir = new File(saveFile);

if (!(dir.exists()) && !(dir.isDirectory())) {
boolean created = dir.mkdirs();
if (created) {
System.out.println("创建文件夹成功!");
} else {
System.out.println("创建文件夹失败!");
}
}

int lastIndex = strURL.lastIndexOf("/");
saveFile = saveFile + strURL.substring(lastIndex + 1);

URL url = new URL(strURL);
URLConnection con = url.openConnection();
long len = con.getContentLength();

con.connect();
bis = new BufferedInputStream(con.getInputStream());
fos = new FileOutputStream(saveFile);

int size = 0;
int progress = 0;
while ((size = bis.read(buf)) != -1) {
// System.out.print("_");
fos.write(buf, 0, size);
progress++;
System.out.print(".");
if (progress % 80 == 0) {
System.out.print("\n");
progress = 0;
}
}
fos.close();
bis.close();

File fsaved = new File(saveFile);
long fileLen = fsaved.length();

if (progress > 0)
System.out.print("\n");
System.out.println(len);
System.out.println(fileLen);

if (len == fileLen) {
return true;
} else {
return false;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

return false;
}

/**
* Specific download
*/
public void downloadSite() {
final int V = 34;

final int MAX_TUNES = 20;

int total = 0, failed = 0, success = 0;

for (int i = 1; i <= MAX_TUNES; i++) {
String strURL = ...

String saveFile = ...

System.out.println(strURL);
boolean successful = downloadSrc(strURL, saveFile);
total ++;
if (successful) {
success++;
System.out.println("Done - " + saveFile + "\n");
} else {
failed++;
System.out.println("Failed.\n");
}
}
System.out.println("Total: " + total + "; succeed: " + success + "; failed: " + failed);
}

public static void main(String[] args) {
DownloadMP3 dlmp3 = new DownloadMP3();
dlmp3.downloadSite();
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值