Java从URL下载文件
/**
* @param filePath 文件将要保存的目录
* @param url 请求的路径
* @return
* @从制定URL下载文件并保存到指定目录
*/
public static File saveUrlAs(String url, String filePath) {
//为下载的文件命名
String fileName = url.substring(url.lastIndexOf("/") + 1);
//创建保存的文件目录
File file = new File(filePath);
//判断文件夹是否存在
if (!file.exists()) {
//如果文件夹不存在,则创建新的的文件夹
file.mkdirs();
}
InputStream inputStream = null;
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
// 建立链接
URL httpUrl = new URL(url);
conn = (HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表单,默认get方式
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用缓存
conn.setUseCaches(false);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream = conn.getInputStream();
bis = new BufferedInputStream(inputStream);
//写入到文件(注意文件保存路径的后面一定要加上文件的名称)
fileOut = new FileOutputStream(filePath + fileName);
bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = bis.read(buf);
//保存文件
while (length != -1) {
bos.write(buf, 0, length);
length = bis.read(buf);
}
bis.close();
bos.close();
fileOut.close();
inputStream.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
System.out.println("抛出异常!!");
}
return file;
}
/**
* @param args
*/
public static void main(String[] args) {
String photoUrl = "http://localhost:8204/SafetyStandards/标准化相关文件/图片文件/安全管理平台/道路危险货物运输企业安全标准化资料/1-安全目标/1.1安全工作方针与目标/安全生产方针、目标管理制度/安全生产方针、目标管理制度-1.png";
String filePath = "D:/hh2/"; //保存目录
File file = saveUrlAs(photoUrl, filePath);
}
参考:https://blog.csdn.net/xiao714041/article/details/80524056