Java:获取网络资源文件的文件大小

时间:2024-02-23 20:11:28
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; } }