/**
* Download the file from the specified URL and save it to the specified directory
*
* @param url Requested URL
* @param filePath The directory where the file will be saved
* @param method GET or POST
* @param fileName
* @return
*/
public static File saveUrlAs(String url, String filePath, String method, String fileName) {
// Create different folder directories
File file = new File(filePath);
// Determine whether the folder exists
if (!file.exists()) {
// If the folder does not exist, a new folder is created
file.mkdirs();
}
FileOutputStream fileOut = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
// Establish link
URL httpUrl = new URL(url);
conn = (HttpURLConnection) httpUrl.openConnection();
// Submit the form in post mode. The default mode is get
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
// Cache cannot be used in post mode
conn.setUseCaches(false);
// Connect to the specified resource
conn.connect();
// Get network input stream
inputStream = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(inputStream);
// Judge whether the saving path of the file ends with /
if (!filePath.endsWith("/")) {
filePath += "/";
}
// Write to file (note that the file name must be added after the file saving path)
fileOut = new FileOutputStream(filePath + fileName);
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
byte[] buf = new byte[4096];
int length = bis.read(buf);
// save file
while (length != -1) {
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
从指定的URL下载文件并将其保存到指定的目录
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 原文:软测小生ruancexiaosheng 关注领取福利教程CSDN博客原文 上一篇博客写到当不能使用Sele...
- /*________保存图片到沙河路径文件夹_____________**littleSun_zheng**/ /...
- ls /etc/*.conf | cut -d / -f3 | tr ‘a-z' 'A-Z' > /tmp/etc...