/**
* 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...