public static void main(String[] args) throws IOException {
String savePath = ".\\src\\main\\resources\\download";
String path = "http://xxxxxx?xxxxxx.pdf";
downLoadFromUrl(path, path.substring(path.lastIndexOf("?") + 1), savePath);
}
/**
* 下载文件
*
* @param urlStr 文件路径
* @param fileName 文件名
* @param savePath 保存路径
* @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 = conn.getInputStream();
byte[] getData = readInputStream(inputStream);
//文件保存位置
File saveDir = new File(savePath);
if (!saveDir.exists()) {
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 = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 删除文件
*
* @param file 文件
* @return 成功->true 失败->false
*/
public static boolean delFile(File file) {
if (!file.exists()) {
return false;
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
delFile(f);
}
}
}
return file.delete();
}
网友评论