为了直观展示,方法中指定了文件后缀为.jpg,只下载图片
如果下载其他格式文件的话指定其他后缀,或把要输出的文件名也改成参数
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
//---------------------------------------------------------
public static String download(String urlString) {
InputStream is = null;
FileOutputStream os = null;
try {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
// 输入流
is = con.getInputStream();
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
String filename = System.getProperty("os.name").toLowerCase().contains("win") ? System.getProperty("user.home") + "\\Desktop\\temp.jpg" : "/home/project/temp.jpg";
File file = new File(filename);
os = new FileOutputStream(file, true);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
return filename;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//从微信下载图片时如果没有id对应的图片则下载一个空图片,不会存在返回为null的情况
return null;
}
有下载肯定要有删除,也以删除图片为例,可根据需要自行调整
public static Boolean deleteImage() {
File file = new File(System.getProperty("os.name").toLowerCase().contains("win") ? System.getProperty("user.home") + "\\Desktop\\temp.jpg" : "/home/project/temp.jpg");
return !file.exists() || file.delete();
}
//------------------业务中我是这样用的删除----------------------------
private Boolean deleteImage() {
int i = 0;
boolean flag = deleteImage();
while (i >= 3 || !flag) {
i++;
flag = deleteImage();
}
return flag;
}