Java根据URL链接下载⽂件图⽚到本地相关⼯具类代码
import java.io.*;
import java.URL;
import java.URLConnection;
/**
* @description: 根据⽂件链接地址下载⽂件
* @author: zyb
* @date: 2020/10/13 15:47
*/
public class DownloadFile {
public static void main(String[] args) {
downloadA("⽂件链接地址", "下载存放地址 + ⽂件名+后缀");
downloadB("⽂件链接地址", "⽂件名+后缀", "下载存放地址");
}
/**
* 根据链接地址下载⽂件
* @param downloadUrl ⽂件链接地址
* @param path 下载存放⽂件地址 + ⽂件名
*/
private static void downloadA(String downloadUrl,String path) {
URL url = null;
DataInputStream dataInputStream = null;
FileOutputStream fileOutputStream = null;
try {
url = new URL(downloadUrl);
dataInputStream = new DataInputStream(url.openStream());
fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = ad(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.ByteArray());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
getsavefilename* @param downloadUrl ⽂件链接地址
* @param filename 保存⽂件名
* @param filePath 保存⽂件路径
*/
private static void downloadB(String downloadUrl, String filename, String filePath) {
URL url = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论