从某网站下载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();
}
}