Skip to content

Commit

Permalink
UrlResource增加size方法
Browse files Browse the repository at this point in the history
  • Loading branch information
looly committed Jul 29, 2023
1 parent e8c1f7a commit d179823
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* 【core 】 ZipReader增加setMaxSizeDiff方法,自定义或关闭ZipBomb(issue#3018@Github)
* 【db 】 Query.of(entity)构建时传入fields(issue#I7M5JU@Gitee)
* 【db 】 clickhouse驱动名称变更为com.clickhouse.jdbc.ClickHouseDriver(issue#3224@Github)
* 【core 】 UrlResource增加size方法(issue#3226@Github)

### 🐞Bug修复
* 【core 】 修复MapUtil工具使用filter方法构造传入参数结果问题(issue#3162@Github)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
package cn.hutool.core.io.resource;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;

import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.io.*;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

/**
* URL资源访问类
Expand Down Expand Up @@ -104,4 +104,14 @@ public File getFile(){
public String toString() {
return (null == this.url) ? "null" : this.url.toString();
}

/**
* 获取资源长度
*
* @return 资源长度
* @since 5.8.21
*/
public long size() {
return URLUtil.size(this.url);
}
}
47 changes: 47 additions & 0 deletions hutool-core/src/main/java/cn/hutool/core/util/URLUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -776,4 +776,51 @@ public static String getDataUri(String mimeType, Charset charset, String encodin

return builder.toString();
}

/**
* 获取URL对应数据长度
* <ul>
* <li>如果URL为文件,转换为文件获取文件长度。</li>
* <li>其它情况获取{@link URLConnection#getContentLengthLong()}</li>
* </ul>
*
* @param url URL
* @return 长度
* @since 6.0.0
*/
public static long size(final URL url) {
if (URLUtil.isFileURL(url)) {
// 如果资源以独立文件形式存在,尝试获取文件长度
final File file = FileUtil.file(url);
final long length = file.length();
if (length == 0L && !file.exists()) {
throw new IORuntimeException("File not exist or size is zero!");
}
return length;
} else {
// 如果资源打在jar包中或来自网络,使用网络请求长度
// issue#3226, 来自Spring的AbstractFileResolvingResource
try {
final URLConnection con = url.openConnection();
useCachesIfNecessary(con);
if (con instanceof HttpURLConnection) {
final HttpURLConnection httpCon = (HttpURLConnection) con;
httpCon.setRequestMethod("HEAD");
}
return con.getContentLengthLong();
} catch (final IOException e) {
throw new IORuntimeException(e);
}
}
}

/**
* 如果连接为JNLP方式,则打开缓存
*
* @param con {@link URLConnection}
* @since 6.0.0
*/
public static void useCachesIfNecessary(final URLConnection con) {
con.setUseCaches(con.getClass().getSimpleName().startsWith("JNLP"));
}
}

0 comments on commit d179823

Please sign in to comment.