admin管理员组文章数量:1606465
为了直观展示,方法中指定了文件后缀为.jpg,只下载图片
如果下载其他格式文件的话指定其他后缀,或把要输出的文件名也改成参数
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.URL;
import java.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;
}
版权声明:本文标题:Java根据url下载文件到本地 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728498983a1160968.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论