工具类代码
package com.example.util;
import org.apache.commons.io.FileUtils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* 文件相关工具类
*/
public class FileUtil {
/**
* 获取网络文件的大小
* @param fileUrl
* @return
*/
public static int getFileSize(String fileUrl) {
if (fileUrl == null || "".equals(fileUrl)) {
return 0;
}
int fileSize = 0;
URL url = null;
URLConnection conn = null;
try {
url = new URL(fileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
try {
conn = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
fileSize = conn.getContentLength();
}
return fileSize;
}
}
测试示例
package com.example.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FileUtilTest {
@Test
void getFileSize() {
String fileUrl = "https://pdf.dfcfw.com/pdf/H3_AP202402221622830899_1.pdf?1708673604000.pdf";
int fileSize = FileUtil.getFileSize(fileUrl);
System.out.println(fileSize); // 435324 == 425 KB
}
}