Java下载⽹络资源⽂件 public static void main(String[] args) throws IOException {
String savePath = ".\\src\\main\\resources\\download";
String path = "xxxxxx?xxxxxx.pdf";
downLoadFromUrl(path, path.substring(path.lastIndexOf("?") + 1), savePath);
}
/**
* 下载⽂件
*
* @param urlStr ⽂件路径
* @param fileName ⽂件名
* @param savePath 保存路径
getsavefilename* @throws IOException
*/
public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException { URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 超时时间设置
conn.setConnectTimeout(15 * 1000);
InputStream inputStream = InputStream();
byte[] getData = readInputStream(inputStream);
//⽂件保存位置
File saveDir = new File(savePath);
if (!ists()) {
saveDir.mkdir();
}
File file = new File(saveDir + File.separator + fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
fos.close();
inputStream.close();
// 删除⽂件
// boolean delFile = delFile(saveDir);
}
/**
* 从输⼊流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((len = ad(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
ByteArray();
}
/**
* 删除⽂件
*
* @param file ⽂件
* @return 成功->true 失败->false
*/
public static boolean delFile(File file) {
if (!ists()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
delFile(f);
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论