展开全部
举例代码:/**
* 下载文件。
* @param urlStr 文件的URL
* @param savePath 保存到62616964757a686964616fe4b893e5b19e31333365656662的目录
* @param fileName 保存的文件名称
* @param description 描述(如:歌曲,专辑封面,歌词等)
* @throws IOException
*/
public static void downLoad(String urlStr, String savePath, String fileName, String description) throws IOException
{
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(100000); // 设置超时间为10秒
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 防止屏蔽程序抓取而返回403错误
File saveDir = new File(savePath);
File file = new File(saveDir + File.separator + fileName);
try (InputStream inputStream = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file))
{
byte[] flowData = readInputStream(inputStream);
fos.write(flowData);
} catch (Exception e) {
MainFrame.logEvent("字节保存时出现意外:" + e.getMessage());
}
MainFrame.logEvent(description + "下载完成:" + url);
}
MainFrame.logEvent()是我自己弄的日志记录而已,可以忽略不看